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.
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.
This should do the job, which you're looking for. Rest you can make a file and print the response. I am just representing the thing which you want for now:
class Test:
# this is responsible for the count
counter = 0
def __init__(self):
Test.counter += 1
self.id = Test.counter
t = Test()
t2 = Test()
print(Test.counter)
# OUTPUT => 2
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.