简体   繁体   English

Python-将类实例名称添加到列表

[英]Python - Adding class instance name to a list

Each time I instantiate an object of the class, I want to add the instance to a list 每次实例化类的对象时,我都想将实例添加到列表中

example_obj_list = []

class RandomObject:
    def __init__(self, some_property):
        self.some_property = some_property

x = RandomObject('purple')
y = RandomObject('blue')
z = RandomObject('brown')

How do I add a step to __init__ so that it automatically appends each object to the list? 如何在__init__添加步骤,以便它自动将每个对象追加到列表中?

If you're going to do this within the class, then the list should be a class object: 如果要在类中执行此操作,则列表应为类对象:

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)

Output: 输出:

purple
blue
brown

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM