First page Back Continue Last page Overview Graphics

Counting Instances

class C:

counter = 0 def __init__(self):

C.counter += 1

def __del__(self):

""" called before an element is destroyed """

C.counter -= 1

if __name__ == "__main__":

x = C()

print("Number of instances: : " + str(C.counter))

y = C()

print("Number of instances: : " + str(C.counter))

del x

print("Number of instances: : " + str(C.counter))

del y

print("Number of instances: : " + str(C.counter))

Output:

$ python3 counting_instances.py

Number of instances: : 1

Number of instances: : 2

Number of instances: : 1

Number of instances: : 0