Categories
Python Answers

How to print all instances of a class with Python?

Spread the love

Sometimes, we want to print all instances of a class with Python.

In this article, we’ll look at how to print all instances of a class with Python.

How to print all instances of a class with Python?

To print all instances of a class with Python, we can use the instances property.

For instance, w write

class A:
    instances = []
    def __init__(self):
        self.__class__.instances.append(self)

to create the A class with the instances attribute list.

Then we call self.__class__.instances.append to append self to the instances attribute when we create an A instance.

Then we can get the value of instances with

print('\n'.join(A.instances))

to print all instances of class A created.

Conclusion

To print all instances of a class with Python, we can use the instances property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *