Home » Python programs

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.

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 code 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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.