如何以列表形式访问、修改和验证子类中的值



请原谅主题行,如果它不能准确描述我正在做的事情。我不知道还能如何描述它。

我有一个包含子类的类。在子类中有一个值,它是一个列表。使用我的主类,我希望能够检索和设置该列表中的每个单独值。下面的代码是我正在尝试执行的操作的示例,显然不起作用:

在这个例子中,我有一辆车。每辆车都有四个轮胎。 我希望能够单独检索和设置汽车每个车轮上的轮胎类型。我还希望进行验证,以防止我在汽车上放置不需要的轮胎(Firestone(。

class Car:
def __init__(self, model: str):
self._model = model
self._tires = self.Tires()
class Tires():
def __init__(self):
# Default to no tires on the car
self._tires = ["", "", "", ""]
# Create my car
my_car = Car("LeSabre")
# Put four tires on my car. I don't want Firestones, so it should error on the last two tires. How to validate???
my_car.Tires[0] = "Goodyear"
my_car.Tires[1] = "Goodyear"
my_car.Tires[2] = "Firestone"
my_car.Tires[3] = "Firestone"
# What is the second tire on my car?
print(my_car.Tires[1])

您可以使用UserListpython库列表包装器。其项存储在data属性的基础列表中。

修改后的源代码:

import collections
from collections import UserList
class Car:
def __init__(self, model: str):
self._model = model
self._tires = self.Tires()
class Tires(UserList):
def __init__(self):
self.data = ["", "", "", ""]
my_car = Car("LeSabre")
my_car._tires[0] = "Goodyear"
my_car._tires[1] = "Goodyear"
my_car._tires[2] = "Firestone"
my_car._tires[3] = "Firestone"
print(my_car._tires[1])

打印Goodyear

感谢您的评论。它帮助我了解了我想做的事情。这就是我想出的。它可能不是最好的,也不是最漂亮的,但它有效......

我绝对愿意对此代码发表评论。

class Car:
def __init__(self, model: str):
self._model = model
self._tires = ["", "", "", ""]
def tires(self, tires: list = None) -> list:
"""
:param tires: A list of four tires to put on the car
:return: A list of tires on the car
"""
# If we specified some tires...
if tires is not None:
# ... there must be 4 of them
if len(tires) != 4:
raise Exception("Wrong number of tires for a car")
# Change all four tires
for t in range(0, 4):
self.tire(t, brand=tires[t])
return self._tires
def tire(self, index:int, brand: str = None):
"""
:param self:
:param index: Which tire are we accessing
:param brand: What brand of tire are we putting on
:return: The brand of tire at that index
"""
# There can only be four tires
if index < 0 or index > 3:
raise Exception("Invalid tire selected")
if brand is not None:
# Make sure they don't put a Firestone on my car
if brand == "Firestone":
raise Exception("Don't use Firestone tires")
else:
self._tires[index] = brand
return self._tires[index]
# Create my car
my_car = Car("LeSabre")
# Put four tires on my car. I don't want Firestones, so it should error on the last two tires. How to validate???
my_car.tire(0, "Goodyear")
my_car.tire(1, "Goodyear")
my_car.tire(2, "Uniroyal")
my_car.tire(3, "Uniroyal")
# What is the third tire on my car?
print(my_car.tire(2))
# What are all the tires on my car?
print(my_car.tires())
# Put a Firestone on my car
my_car.tire(1, "Firestone")

最新更新