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

How can I create an object that contains instances of a class in Python?

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

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

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

这个答案的灵感来自 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']"""

我认为你可以这样做:

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() 来保存汽车列表(您可以向其添加、删除等)。在那个 class 中,添加一个 get_prizes() 方法,通过遍历列表来 returns 奖品列表。例如:

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']

如果需要,您可以在每个对象中添加更多的输入检查,但这是基本框架。希望对您有所帮助,编码愉快!