What is a destructor in Python?

A destructor method is called when all references to an object have been destroyed. In Python, the __del__() method is referred to as a destructor method.

Destructors aren’t as important in Python as they are in C++, because Python contains a garbage collector that takes care of memory management automatically.

Syntax

def __del__(self):
  # body of destructor

When an object is no longer referenced or the program finishes, a reference to it is likewise erased.

Code

The following code shows how to use the __del__() function and the del keyword to delete all of the object’s references, triggering the destructor to execute automatically.

class Student:
# Initializing class named Student
def __init__(self):
print('The class named Student was created.')
# Calling destructor
def __del__(self):
print('The destructor is called. Student is deleted.')
sObj = Student()
del sObj

Explanation

In the code, the destructor was executed after the references to the object were destroyed or the program terminated.

Example 2

The following code shows when a destructor is invoked:

class Student:
# Initializing class named Student
def __init__(self):
print('The class named Student was created.')
# Calling destructor
def __del__(self):
print('The destructor is called. Student is deleted.')
def Create_obj():
print('*** Creating Object ***')
s_Object = Student()
print('***End of Function***')
return s_Object
print('***Calling Create_obj()***')
myObj = Create_obj()
print('***Program Ends***')

Free Resources