Search code examples
pythonpython-3.xclassinstance

How can I know how many instances were made from a class?


I tried this program:

class Test():
    def __init__(self):
        self.value = 10
        print(self.value)

t = Test()
t2 = Test()

I would like to know how many instances were made from the Test class.


Solution

  • The idea to create a counter for the class and increment them if a new instance is created, works in most cases.

    However, you should keep some aspects in mind. What if a instance is removed? There is no mechanism to decrease this counter. To do this, you could use the __del__ method, which is called when the instance is about to be destroyed.

    class Test:
        counter = 0
        def __init__(self):
            Test.counter += 1
            self.id = Test.counter
        def __del__(self):
            Test.counter -= 1
    

    But sometimes it can be problematic to find out, when an instance is deleted. In this blog post you can find some more information if needed.