Write a python program to Parameterized Constructor and Destructor


The program defines a Student class with a constructor and a destructor. It creates three instances of the class, displays their details, and then explicitly deletes these instances to demonstrate the destructor's functionality. Here's a breakdown of the code:

  • class Student: This class defines a student with attributes such as roll_number, name, and per (percentage).
  • __init__(self, roll_number, name, per): The constructor initializes a Student object with the provided roll_number, name, and per.
  • display_details(self): This method is used to print the details of a student, including their roll number, name, and percentage.
  • __del__(self): This special method is the destructor. It is automatically called when an instance of the class is deleted. In this case, it prints a message indicating the roll number of the student being deleted.
  • Three instances of the Student class (s1, s2, and s3) are created and initialized with different data for each student.
  • The code displays the details of each student by calling the display_details method for each instance.
  • The instances are explicitly deleted using the del statement, which triggers the __del__ destructor method.

Here's what the code does:

  • It creates three student objects with different details.
  • It prints the details of each student using the display_details method.
  • It explicitly deletes each student object, which triggers the destructor and prints a message indicating that the student is being deleted.

Source Code

class Student:
	def __init__(self, roll_number, name, per):
		self.roll_number = roll_number
		self.name = name
		self.per = per
 
	def display_details(self):
		print("Roll Number :", self.roll_number)
		print("Name :", self.name)
		print("Percentage :",self.per)
 
	def __del__(self):
		print("Deleting student with Roll Number", self.roll_number)
 
# Creating objects of the Student class with a parameterized constructor
s1 = Student(501, "Kim", 85.5)
s2 = Student(502, "Bob", 78.0)
s3 = Student(503, "Tin", 90.3)
 
print("Student 1 Details :")
s1.display_details()
 
print("\nStudent 2 Details :")
s2.display_details()
 
print("\nStudent 3 Details :")
s3.display_details()
 
# Deleting student objects (calling the destructor)
del s1
del s2
del s3

Output

Student 1 Details :
Roll Number : 501
Name : Kim
Percentage : 85.5

Student 2 Details :
Roll Number : 502
Name : Bob
Percentage : 78.0

Student 3 Details :
Roll Number : 503
Name : Tin
Percentage : 90.3
Deleting student with Roll Number 501
Deleting student with Roll Number 502
Deleting student with Roll Number 503

Example Programs