我想创建一个包含类的某些实例的对象。该对象应该是实例的某种列表概括。例如。我有以下课程:
class car:
def __init__(self, prize, color)
self.prize = prize
self.color = color
现在我想拥有一个对象cars
,其中包含很多car类的实例,但我可以像car的实例一样使用它,即cars.prize
应该返回我所收集的所有实例的奖品列表。该对象cars
。
我认为您可以执行类似的操作:
class Cars:
def __init__(self, list_of_cars):
self.cars_list = list_of_cars
self.prize = [car.prize for car in self.cars_list]
self.color = [car.color for car in self.cars_list]
让我们看看如何使用它:
list_of_cars = [Car(1000, "red"), Car(2000, "blue"), Car(3000, "Green")]
x = Cars(list_of_cars)
print(x.prize)
# [1000, 2000, 3000]
print(x.color)
#["red", "blue", "Green"]
您可以创建一个新的class car_list()
,其中包含汽车列表(您可以在其中添加,移除等)。在该类中,添加一个get_prizes()
方法,该方法通过遍历列表来返回奖品列表。例如:
class car_list():
def __init__(self, cars):
self.cars = cars # This is a list
def get_prizes(self):
return [car.prize for car in self.cars]
代码中的小错误::
方法定义行的末尾需要__init__
:def __init__(self, prize, color):
这里是cars
的实现,它可以完成您想要的。通过使用@property
装饰器,您可以将方法作为对象属性进行访问:
class car:
def __init__(self, prize, color):
self.prize = prize
self.color = color
class cars:
def __init__(self, list_of_cars):
for one_car in list_of_cars:
assert isinstance(one_car, car) # ensure you are only given cars
self.my_cars = list_of_cars
@property
def prize(self):
return [one_car.prize for one_car in self.my_cars]
@property
def color(self):
return [one_car.color for one_car in self.my_cars]
>>> a = car('prize1', 'red')
>>> b = car('prize2', 'green')
>>> c = car('prize3', 'azure')
>>> carz = cars([a,b,c])
>>> carz.prize
['prize1', 'prize2', 'prize3']
>>> carz.color
['red', 'green', 'azure']
如果需要,可以在每个对象中的输入上添加更多检查,但这是基本框架。希望对您有所帮助,快乐编码!