Updated March 17, 2023
Introduction to Destructor in Python
Destructor in a program plays the role of reversing the operations performed by the constructor used for clearing the object of the class created by the constructor program. Like any other object-oriented programming language applied for the development of a system or web-based application, Python allows almost all the functional features dealt with classes and objects. Destructors are primarily employed as a tidying method in the programs, as a way to organize the code and implement the coding standards. Destructors are defined with ‘__del__()’ as the python code’s keyword.
Syntax:
def __del__(self):
#destructor body
As one can see, __del__ is the keyword used to define destructor. When it is called, all reference to that object gets deleted which also known as garbage collection.
Examples of Destructor in Python
Let’s see different examples of destructor in python to get a better understanding:
Example #1
Code:
class Grocery:
# Initializing
def __init__(self):
print('Grocery created.')
# Deleting (Calling destructor)
def __del__(self):
print('Destructor called, Grocery deleted.')
obj = Grocery()
del obj
Output:
“Grocery” is the class defined with its special methods: constructor & destructor.
So, one can see once the object of the class “Grocery” is created. It automatically invokes __init__, which is the constructor of the class. However, when “del obj” gets executed to delete an object, the destructor method automatically gets called.
Example #2
Code:
class Text:
def __del__(self):
print ('Text deleted')
a = Text()
del a
a = Text()
b = a
del b
del a
Output:
Text is a class, “a” is an object reference to the class. “b” local copy of that reference “a”. So when b is deleted, the method doesn’t get called, as it simply holds the local copy.
Advantages of Destructor in Python
As said before, the destructor is not as much used in python as much as it is used in Java, C++. However, the concept remains the same. Here are some advantages of using it in programs:
- Unneeded objects get deleted automatically. This frees the memory space, which is known as the Garbage collection.
- The advantage also lies in the fact that it invokes automatically.
Certain steps that should be taken care of while using destructor:
1. Python doesn’t know the order in which destroying objects will be safer that can hold circular references to each other. Because of this, people recommend using “close” explicitly after every function. But in case of exceptions occurs, managing the close method gets troublesome. Hence using destructors is better, keeping in mind the cyclic references.
2. Cyclic references if it doesn’t get handled well, chances are of leaky abstractions, plus bad design.
The best thing is: resources should be handled by the lowest level object of the class.
3. When someone is in dire need of using cyclic references to objects in complex code, Python provides a good solution to it in the form of module name: weakref. That means weak references are provided to the referent, which ultimately helps implement cache and no longer keep the large object alive. When a large object is not alive, that means it appears in the cache.
Let’s see it through a small code to get a lucid understanding:
Code:
import weakref
class C:
def method(self):
print("Hi!method called!")
c = C()
r = weakref.ref(c)
print(c)
print(r)
Output:
As one can see, “r” is a weak reference to the object “c”.
If we make a method reference to “r” like c2 = r(). Then “c” and “c2” should be the same because they refers to the same. See the example shown below:
In the case of the deletion of the main object, the reference object loses its existence. See the example shown below:
As one can notice, print(r()) results is “None”. In that case:
gc.collect() will result into 0.
4. __del__ should not get confused with del in python. __del__ is a special method of a destructor class, and “del” is used to destroy a variable defined in the python environment. Both are two completely different things.
Like:
xx = 10
del xx
Conclusion
After going through the above content, we can say constructors and destructors are a crucial part of Python. Destructor plays a pivotal role in managing the memory, where it performs many cleaning tasks on objects used in programming. Dealing with small programs may not give you the actual picture behind using destructors. However, while dealing with production-level programs or any complex lines of code, destructors’ importance can be understood clearly, as memory usage becomes very important there. Keeping in mind the idea of cyclic reference can absolutely lead to good design while working with destructors.
Recommended Articles
This is a guide to Destructor in Python. Here we discuss the basic concept, advantages along with the different examples of python destructor. You may also look at the following articles to learn more –