DEV Community

Shivani tiwari
Shivani tiwari

Posted on

Write a program to create a class count objects and calculate the number of objects that has been created in realtime.

Hey Everyone,

so today we discuss about the how can we count the object of any class
There is few steps below-

  1. First we create the class count_objects

  2. Then we will initialize class variable (count=0) because we want to count the objects not methods

  3. Then we create the constructor we create always by using init (constructor)

4.Than Create an object of count_objects class with attributes

5.And Finally print the total number of object available in
count_objects class

here lets see the Example-

# Create a count_objects class
class count_objects:

    # initialise class variable
    count = 0

    # Constructor method

    def __init__(self, name, age):

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

        # incrementing the class variable by 1
        # whenever new object is created
        count_objects.count += 1

    # Create a method for printing details

    def printDetails(self):

        print(, self.age, "years old")

# Create an object of Student class with attributes

student1 = count_objects('Ankit Rai', 22)
student2 = count_objects('Aishwarya', 21)
student3 = count_objects('Shaurya', 21)
student4 = count_objects('shiv', 1)

# Print the total no. of objects cretaed

print("Total number of objects created: ", count_objects.count)
Enter fullscreen mode Exit fullscreen mode

So you can copy that code and print in your editor which editor you use and then see the result .

I hope this Answer will help you to solve your problem so if you like the article so just like and share the post

Follow for more updates and visit -

Thank you Everyone
Shivani Tiwari

Top comments (1)

iamjaydev profile image