How to use destructors in Python

In this article, we will discuss how to use destructors in Python. If you are familiar with Object-Oriented Programming, you might have a thing or two about constructors and destructors. However, we will have a short recap of what these terms mean. Let’s dive right in!

What are destructors?

Whenever you create an object, the constructor of the class is called either implicitly or explicitly. The purpose of the constructor is to initialize the object with the default values for its attributes. On the other hand, the destructor does the opposite, it is used to destroy the object i.e, to remove the object from memory.

Destructors in Python:

Python uses certain methods for these purposes. These methods start and end with “__” for example __init__() is used to represent the constructor. Similarly, __del__() is used to represent the destructor. The destructor takes self as the default argument.

This method is called every time the del keyword is used to delete an object or when the garbage collector finds an object with no further references for an object, it will automatically invoke this method to clean up the memory occupied by the object. Let’s see a sample usage of the same.

class Demo:
    def __init__(self):
        self.status = "Alive"

    # Destructor for the class
    def __del__(self):
        print("The object no longer exists")

obj = Demo()

# The status has been initialized to Alive
print(obj.status)

# This calls the destructor
del obj

"""Running the code with the following line will throw an error
    as the obj no longer exists in the memory."""
# print(obj.status)

The above will result in the following output:

Alive
The object no longer exists

You need not explicitly call the destructor unless there is a need for it, the garbage collector will take care of the rest. If you uncomment the last line of the code, the code will reference an object that is no longer in memory as the del keyword before it deletes the object from memory.

I hope you found this article useful in understanding how destructors work in Python.

See also:

Leave a Reply

Your email address will not be published. Required fields are marked *