Class Destructor in Python

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.

Example

In this example, we write a program with a class Student. We define the class destructor using __del__() method for Student class.

We create an object of type Student, and then delete this object.

Python Program

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
Run Code Copy

Output

Destructor called for Ram

When the 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 with statement.

Summary

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.

Related Tutorials

Code copied to clipboard successfully 👍