turret-detected
turret-detected

Reputation: 3

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?

Upvotes: 0

Views: 705

Answers (1)

Prune
Prune

Reputation: 77837

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

Upvotes: 2

Related Questions