Python Destructors to Destroy the Object

Python destructors are special methods that are called automatically just before an object is destroyed. Alternatively, they are referred to as finalizers or del() methods. Destructors are useful for releasing resources, closing files, terminating processes, or performing other cleanup tasks before an object is destroyed.

This post provides an in-depth guide on how to destroy the object using Python destructors. Let’s start with the following contents:

  • Create a Destructor in Python
  • Using Destructor in Recursive Function
  • Using Destructor in Circular Reference

How to Create a Destructor in Python?

To define a destructor in Python, you must create a special method called del() in the class definition. Here is how to create a Python destructor:

Code:

class ABC:
    def __init__(self):
        print ("Object created");

    # destructor
    def __del__(self):
        print ("Object destroyed");
obj = ABC();
del obj;
  • The class named “ABC” was created. 
  • The constructor method “__init__ “ of the class displays the message “Object created” when a class object is created.
  • The class’s destructor method “__del__” displays the message “Object destroyed” when the object is destroyed.
  • The object named “obj” of the ABC class is created.
  • Lastly, the del keyword is used to delete the object “obj,” and the destructor method __del__ is called automatically.

Output:

The above snippet verified that the object is created and destroyed.

How to Use a Destructor in Recursive Function?

The below example code demonstrates how to utilize a destructor in a recursive function:

Code:

class RecursiveFunction:
    def run(self, n):
        if n <= 0:
            return
        print("Running recursive function with n =", n)
        self.run(n-1)
       
    def __del__(self):
        print("Recursive function object destroyed")
# Create an object of the class
obj = RecursiveFunction()
# Call the recursive function
obj.run(5)
del obj
  • The ” RecursiveFunction ” class is defined with two methods in the program.
  • The first method, “run(self, n),” takes an integer argument “n” and recursively calls itself with the argument “n-1” until n becomes less than or equal to 0. 
  • The second method,” __del__(self),” is called when the class object is destroyed.
  • The object of the class calls the method recursively by accepting “5” as an argument.
  • The “__del__()” method is called automatically when the del keyword deletes the object named “obj”.

Output:

The RecursiveFunction object has been destroyed successfully.

How to Use a Destructor in Circular Reference?

In Python, destructors can be used to deal with circular references. A circular reference happens when two or more objects refer to each other in a way that creates an infinite loop. 

In the case of multiple objects referencing each other, their reference count never drops to zero, and the garbage collector never destroys them. To destroy these objects, we use destructors in the program.

Here is an example code:

Code: 

class MyClassA:
    def __init__(self, obj_b):
        self.obj_b = obj_b
       
    def __del__(self):
        print("Object A destroyed")
       
class MyClassB:
    def __init__(self):
        self.obj_a = None
       
    def __del__(self):
        print("Object B destroyed")
       
obj_b = MyClassB()
obj_a = MyClassA(obj_b)

del obj_a
del obj_b
  • The two classes named “MyClassA” and “MyClassB” are defined in the program.
  • The “MyClassA” takes an object of “MyClassB” as a parameter and stores it in the instance variable “obj_b.”
  • The “MyClassB” has an instance variable “obj_a,” which is initialized to None.
  • The destructor methods of both classes use the “__del__” keyword to call their respective destructors.
  • The code creates an instance of “MyClassB” and assigns it to “obj_b.”
  • The instance of “MyClassA” is created by accepting the “obj_b” as the argument and assigned to “obj_a”.
  • The “del obj_a” and “del obj_b” statements are used to destroy the instances of the classes.
  • Whenever the class instances are deleted, their destructor methods are triggered, which delete all the objects associated with the class.

Output:

The destructor object has been successfully deleted.

Conclusion

The Python destructor is accessed automatically when an object is destroyed or deleted using the del keyword. The Python destructor can perform clean-up tasks such as closing files or releasing network resources. Python destructors can also be used in recursive functions and circular references to destroy the object. This Python guide presented an in-depth guide on Python destructors to destroy the object.