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
class geeks:
counter = 0
def __init__( self ):
geeks.counter + = 1
g1 = geeks()
g2 = geeks()
g3 = geeks()
print (geeks.counter)
|
Output:
3
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
29 Dec, 2020
Like Article
Save Article