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.
def __del__(self):
# body of destructor
When an object is no longer referenced or the program finishes, a reference to it is likewise erased.
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 Studentdef __init__(self):print('The class named Student was created.')# Calling destructordef __del__(self):print('The destructor is called. Student is deleted.')sObj = Student()del sObj
In the code, the destructor was executed after the references to the object were destroyed or the program terminated.
The following code shows when a destructor is invoked:
class Student:# Initializing class named Studentdef __init__(self):print('The class named Student was created.')# Calling destructordef __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_Objectprint('***Calling Create_obj()***')myObj = Create_obj()print('***Program Ends***')