Python program to count the number of objects created

We are executing this program utilizing the idea of classes and objects.

Initially, we make the Class with “Understudy” name with 1 class variable(counter) , 2 occurrence factors or object traits (name and age), the methods are:

Constructor Method: This is made utilizing init inbuilt watchword. The constructor method is utilized to introduce the traits of the class at the hour of object creation.

Object Method: printDetails() is the object method, for making object method we need to go at any rate one parameter for example self catchphrase at the hour of capacity creation. This Object method has no utilization in this program.

For checking the number of objects made of this class, we just need one class variable and one method (which is the constructor method). In this constructor method we increasing the class variable(counter) by one so that, Whenever an object of this class is made, the constructor method is summoned consequently and augmenting the class variable by one.

Python code to count the number of objects created

# Create a Student class
class Student :

    # initialise class variable
    counter = 0

    # Constructor method
    def __init__(self,name,age) :

        # instance variable or object attributes
        self.name = name
        self.age = age

        # incrementing the class variable by 1
        # whenever new object is created
        Student.counter += 1

    # Create a method for printing details
    def printDetails(self) :
        print(self.name,self.age,"years old")

    

# Create an object of Student class with attributes
student1 = Student('Ankit Rai',22)
student2 = Student('Aishwarya',21)
student3 = Student('Shaurya',21)

# Print the total no. of objects cretaed 
print("Total number of objects created: ",Student.counter)

Output

Total number of objects created:  3

Leave a Comment

error: Alert: Content is protected!!