Q:

Python program to count number of objects created

belongs to collection: Python class & object programs

0

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 MethodprintDetails() 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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python class & object programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to check Armstrong number using obj... >>
<< Python program to check prime number using object ...