Wednesday, May 6, 2026
HomeLanguagesHow to count number of instances of a class in Python?

How to count number of instances of a class in Python?

Instances of a class mean the objects created for a particular class. A single class can have multiple objects of it. Here, we will find the count of the number of instances of a class in Python.

Approach:

  • Whenever an object is created, the constructor of that particular class is called.
  • Constructor is a function whose name is the same as that of class name and it doesn’t have any return type. A constructor is used to initialize the variables of a class.
  • Whenever a constructor is called which means a new object is created, we just have to increment a counter that will keep track of the no. of objects that particular class has.
     

Below is the implementation:

Python3




# code
class Lazyroar:
    
    # this is used to print the number
    # of instances of a class
    counter = 0
  
    # constructor of Lazyroar class
    def __init__(self):
        
        # increment
        Lazyroar.counter += 1
  
  
# object or instance of Lazyroar class
g1 = Lazyroar()
g2 = Lazyroar()
g3 = Lazyroar()
print(Lazyroar.counter)


Output:

3
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32513 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6886 POSTS0 COMMENTS
Nicole Veronica
12008 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12104 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7261 POSTS0 COMMENTS
Thapelo Manthata
6974 POSTS0 COMMENTS
Umr Jansen
6960 POSTS0 COMMENTS