w3resource

In a Python class, how do you define a destructor?

Defining destructors in Python classes

In Python, you can define a destructor by creating a special method named '__del__()' within the class. The '__del__()' method is automatically called just before an object is garbage-collected and its memory is deallocated. It allows you to clean or release object resources.

Syntax for defining a destructor in a Python class:

class MyClass:
    # Constructor
    def __init__(self, name):
        self.name = name
    # Destructor
    def __del__(self):
        # Cleanup actions or resource release code
        print(f"{self.name} is being destroyed.")

In the above example, we have a class named "MyClass" with both a constructor ('__init__()' method) and a destructor ('__del__()' method). The constructor initializes object attributes, while the destructor is used to cleanup.

A class instance's constructor '__init()__' is automatically called when an instance is created. When an object becomes garbage-collected and is no longer in use, the destructor '__del()__' is automatically called to perform any necessary cleanup.



Follow us on Facebook and Twitter for latest update.