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 gc module.

For instance, we write:

import gc


class A:
    pass


a1 = A()
a2 = A()
for obj in gc.get_objects():
    if isinstance(obj, A):
        print(obj)

We have the A class and we create 2 instances of it, which we assigned to a1 and a2.

Then we loop through the objects in memory with gc.get_objects with a for loop.

And we check if each obj is an instance of A with isinstance.

If it is, we print it.

Therefore, we see:

<__main__.A object at 0x7f36601f5b80>
<__main__.A object at 0x7f36601f57c0>

from the print output.

Conclusion

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

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 *