Write a python program to count number of objects created


This Python program defines a class called Student and demonstrates the use of class variables, object creation, and instance methods. Here's an explanation of the program:

  • class Student:: This line defines a class named Student.
  • count = 0: This is a class variable named count that is used to keep track of the number of Student objects created. It is initialized to 0.
  • def __init__(self, name, age):: This is the constructor method of the Student class. It is used to initialize the attributes of a Student object. self is a reference to the instance of the class being created, and name and age are the attributes that are set for each object.
  • self.name = name and self.age = age: These lines set the name and age attributes of the Student object to the values passed as arguments.
  • Student.count += 1: This line increments the class variable count by 1 each time a new Student object is created. This is done to keep track of how many Student objects have been created.
  • def GetDetails(self):: This is an instance method of the Student class, which is used to print the name and age of a student.
  • print("Name :", self.name) and print("Age :", self.age): These lines are used to print the name and age of a Student object when the GetDetails method is called.
  • Four instances of the Student class are created:
    • s1 = Student("Sam Kumar", 21) : A Student object is created with the name "Sam Kumar" and age 21.
    • s2 = Student("Tiya", 20): Another Student object is created with the name "Tiya" and age 20.
    • s3 = Student("Sathish", 19): Yet another Student object is created with the name "Sathish" and age 19.
    • s3 = Student("Deepika", 21): An additional Student object is created with the name "Deepika" and age 21. Note that this line reassigns the variable s3, overwriting the previous object created with that variable.
  • print("Number of Objects : ", Student.count) : This line prints the total number of Student objects created by accessing the count class variable. It will reflect the count of objects created, which in this case is 3 since the variable s3 was reassigned.

Source Code

class Student:
	# Class variable to keep track of the number of objects created
	count = 0
 
	def __init__(self,name,age):
		self.name = name
		self.age = age
		Student.count += 1 # Increment the count when an object is created
 
	def GetDetails(self):
		print("Name :",self.name)
		print("Age :",self.age)
 
# Create instances of MyClass
s1 = Student("Sam Kumar",21)
s2 = Student("Tiya",20)
s3 = Student("Sathish",19)
s3 = Student("Deepika",21)
 
# Print the number of objects created
print("Number of Objects : ", Student.count)

Output

Number of Objects :  4

Example Programs