如何在 Python 中创建包含类实例的对象?

我想创建一个包含类的一些实例的对象。该对象应该是实例的某种列表泛化。例如,我有以下课程:

class car:  
  def __init__(self, prize, color)
        self.prize = prize
        self.color = color

现在我想要一个cars包含类汽车的许多实例的对象,但我可以像汽车实例一样使用它,即cars.prize应该返回我在该对象中收集的所有实例的奖品列表cars


三国纷争
浏览 114回答 4
4回答

森林海

我认为你可以这样做: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):&nbsp; &nbsp; instances = {} # cars instances&nbsp; &nbsp; def get_instance():&nbsp; &nbsp; &nbsp; &nbsp; if all_cars not in instances:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # all_cars is created once&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; instances[all_cars] = all_cars()&nbsp; &nbsp; &nbsp; &nbsp; return instances[all_cars]&nbsp; &nbsp; return get_instance@singletonclass all_cars:&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; self.inventory = {}&nbsp; &nbsp; @property&nbsp; &nbsp; def prizes(self):&nbsp; &nbsp; &nbsp; &nbsp; return [e.prize for e in self.inventory.values()]&nbsp; &nbsp; @property&nbsp; &nbsp; def colors(self):&nbsp; &nbsp; &nbsp; &nbsp; return [e.color for e in self.inventory.values()]&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;class car:&nbsp; &nbsp; def __init__(self, prize, color):&nbsp; &nbsp; &nbsp; &nbsp; self.prize = prize&nbsp; &nbsp; &nbsp; &nbsp; self.color = color&nbsp; &nbsp; def register(self):&nbsp; &nbsp; &nbsp; &nbsp; # Like class all_cars is a singleton it is instantiate once, reason why dict is saved&nbsp; &nbsp; &nbsp; &nbsp; cars = all_cars()&nbsp; &nbsp; &nbsp; &nbsp; cars.inventory[len(cars.inventory)] = selfif __name__ == '__main__':&nbsp; &nbsp; # Creating cars items&nbsp; &nbsp; car1 = car("50", "Blue")&nbsp; &nbsp; car2 = car("300", "Red")&nbsp; &nbsp; car3 = car("150", "Gray")&nbsp; &nbsp; # Register part for cars&nbsp; &nbsp; car1.register()&nbsp; &nbsp; car2.register()&nbsp; &nbsp; car3.register()&nbsp; &nbsp; # Like class all_cars is a singleton it is instantiate once, reason why dict is saved&nbsp; &nbsp; cars = all_cars()&nbsp; &nbsp; print(cars.inventory)&nbsp; &nbsp; """{0: <__main__.car object at 0x7f3dbc469400>, ---> This is object car1&nbsp; &nbsp; 1: <__main__.car object at 0x7f3dbc469518>,&nbsp; ---> This is object car2&nbsp; &nbsp; 2: <__main__.car object at 0x7f3dbc469550>}&nbsp; ---> This is object car3"""&nbsp; &nbsp; print(cars.prizes)&nbsp; &nbsp; """['50', '300', '150']"""&nbsp; &nbsp; print(cars.colors)&nbsp; &nbsp; """['Blue', 'Red', 'Gray']"""
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python