每次实例化类的对象时,我都想将实例添加到列表中
example_obj_list = []
class RandomObject:
def __init__(self, some_property):
self.some_property = some_property
x = RandomObject('purple')
y = RandomObject('blue')
z = RandomObject('brown')
如何为__init__
添加一个步骤,以便它自动将每个对象追加到列表中?
答案 0 :(得分:2)
如果要在该类中执行此操作,则列表应该是一个类对象:
class RandomObject:
example_obj_list = []
def __init__(self, some_property):
self.property = some_property
# This is accessing the class attribute (not instance attribute)
self.example_obj_list.append(self)
x = RandomObject('purple')
y = RandomObject('blue')
z = RandomObject('brown')
# Because this was defined at the class level, it can be accessed via the class itself.
for obj in RandomObject.example_obj_list:
print(obj.property)
输出:
purple
blue
brown