How to count the number of class instances in Python

1 Answer

0 votes
class Test:
    counter = 0

    def __init__(self):
        type(self).counter += 1

o1 = Test()
print("instance: " + str(Test.counter))

o2 = Test()
print("instance: " + str(Test.counter))

o3 = Test()
print("instance: " + str(Test.counter))


'''
run:
 
instance: 1
instance: 2
instance: 3
 
'''

 



answered Feb 8, 2018 by avibootz
...