Python program to count number of objects created

Counting objects in python program: Here, we are going to learn how to count the total number of objects created in python?
Submitted by Ankit Rai, on July 20, 2019

We are implementing this program using the concept of classes and objects.

Firstly, we create the Class with "Student" name with 1 class variable(counter) , 2 instance variables or object attributes (name and age), the methods are:

  1. Constructor Method: This is created using __init__ inbuilt keyword. The constructor method is used to initialize the attributes of the class at the time of object creation.
  2. Object Method: printDetails() is the object method, for creating object method we have to pass at least one parameter i.e. self keyword at the time of function creation. This Object method has no use in this program.

Count number of objects created

For counting the number of objects created of this class, we only need one class variable and one method (which is the constructor method). In this constructor method we incrementing the class variable(counter) by one so that, Whenever an object of this class is created, constructor method is invoked automatically and incrementing the class variable by one.

Below is the implementation of the program,

Python program to count 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

Python class & object programs »


Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.