F.E. PPS Unit 5 Practical 5 solution

Practical 5: program to illustrate the use of the __del__() method which is called when an object is about to be destroyed.

Problem Statement

Write a Python program to illustrate the use of the __del__() method which is called when an object is about to be destroyed.

Solution Code

				
					class Employee:
    def __init__(self, name):
        self.name = name
        print(f"Employee {self.name} created.")

    def __del__(self):
        print(f"Employee {self.name} is being destroyed.")

# Creating an object
emp1 = Employee("Alice")

# Deleting the object
del emp1

				
			

Output

The program should print messages when the object is created and destroyed using the __del__() method.

Example Output

				
					Employee Alice created.
Employee Alice is being destroyed.
Process finished with exit code 0
				
			

Explanation

Below is the explanation of F.E. PPS Unit 5 Practical 5 solution where we have written Python program to illustrate the use of the __del__() method which is called when an object is about to be destroyed.

  • __del__() Method: This special method is called when an object is deleted, or when it goes out of scope.
  • del Statement: It deletes the emp1 object and triggers the __del__() method.

Key Concepts Learned

  • Destructor (__del__())
    • The __del__() method is a destructor, which is called when the object is destroyed.
Tech Amplifier Final Logo