Python – Class Destructor
A class destructor is a special method that is called when an object of a class is about to be destroyed.
In Python, the destructor method is defined using the
__del__() method name.
In this tutorial, we will learn how a class destructor can be used in Python, how to define a destructor method in a class, and an example program to demonstrate the same.
Uses of Class Destructor
Class destructor can be used to perform any cleanup actions that are necessary before the object is destroyed. This may include closing open files or database connections, releasing resources, or any other necessary cleanup tasks.
In this example, we write a program with a class
Student. We define the class destructor using
__del__() method for
We create an object of type
Student, and then delete this object.
Run Code Online
class Student: def __init__(self, name, age): self.name = name self.age = age def __del__(self): print("Destructor called for", self.name) # Create an object of type Student student1 = Student("Ram", 12) # Delete the object del student1
Destructor called for Ram
del keyword is used to delete an object, the
__del__() method of that object is called automatically before the object is destroyed.
Things you should know before using Destructor method
It’s important to note that the destructor method is not always guaranteed to be called, and should not be relied upon for critical cleanup tasks.
If the Python interpreter is shut down or the program crashes, the destructor may not be called at all. Therefore, it is generally recommended to use other methods for resource cleanup, such as using context managers or the
In this Python Classes and Objects tutorial, we learned about destructor method in a class, how to define it, and how to invoke it, with example program.