Write a program to create a class count objects and calculate the number of objects that has been created in realtime.
Shivani tiwari
Posted on July 13, 2022
Hey Everyone,
so today we discuss about the how can we count the object of any class
There is few steps below-
First we create the class count_objects
Then we will initialize class variable (count=0) because we want to count the objects not methods
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
self.name = 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.name, 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)
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 -https://codersvillage.com/
Thank you Everyone
Shivani Tiwari
Posted on July 13, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 13, 2024