4 回答

TA貢獻2011條經驗 獲得超2個贊
我認為你可以這樣做:
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"]

TA貢獻1836條經驗 獲得超3個贊
您可以創建一個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]

TA貢獻1868條經驗 獲得超4個贊
代碼中的小錯誤:您需要在方法定義行 :的末尾:__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']
如果需要,您可以在每個對象中添加更多的輸入檢查,但這是基本框架。希望它有所幫助,快樂編碼!

TA貢獻1155條經驗 獲得超0個贊
這個答案的靈感來自 Sam 使用裝飾器的絕妙想法。因此,如果您認為自己對這段代碼感到滿意,請給他打分。
def singleton(all_cars):
instances = {} # cars instances
def get_instance():
if all_cars not in instances:
# all_cars is created once
instances[all_cars] = all_cars()
return instances[all_cars]
return get_instance
@singleton
class all_cars:
def __init__(self):
self.inventory = {}
@property
def prizes(self):
return [e.prize for e in self.inventory.values()]
@property
def colors(self):
return [e.color for e in self.inventory.values()]
class car:
def __init__(self, prize, color):
self.prize = prize
self.color = color
def register(self):
# Like class all_cars is a singleton it is instantiate once, reason why dict is saved
cars = all_cars()
cars.inventory[len(cars.inventory)] = self
if __name__ == '__main__':
# Creating cars items
car1 = car("50", "Blue")
car2 = car("300", "Red")
car3 = car("150", "Gray")
# Register part for cars
car1.register()
car2.register()
car3.register()
# Like class all_cars is a singleton it is instantiate once, reason why dict is saved
cars = all_cars()
print(cars.inventory)
"""{0: <__main__.car object at 0x7f3dbc469400>, ---> This is object car1
1: <__main__.car object at 0x7f3dbc469518>, ---> This is object car2
2: <__main__.car object at 0x7f3dbc469550>} ---> This is object car3"""
print(cars.prizes)
"""['50', '300', '150']"""
print(cars.colors)
"""['Blue', 'Red', 'Gray']"""
添加回答
舉報