-
森林海
我认为你可以这样做: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]
-
MYYA
代码中的小错误:您需要在方法定义行 :的末尾:__init__def __init__(self, prize, color):这是一个实现cars你想要的。装饰器的使用@property允许您将方法作为对象属性进行访问:class car: def __init__(self, prize, color): self.prize = prize self.color = colorclass 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']如果需要,您可以在每个对象中添加更多的输入检查,但这是基本框架。希望它有所帮助,快乐编码!
-
白衣非少年
这个答案的灵感来自 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@singletonclass 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)] = selfif __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']"""