Destructor in Object Oriented Programming (OOPs) in Python Programming

Destructor: Same as constructors, destructor in python are also a special type of method. Destructor in python programming is used to free the extra allocated space by the memory. These spaces are in use during the execution of our programs.
Sometimes, even after the execution of all programs, some memory space is still captured by some of our programs. To free extra consumed spaces, we use destructor in object oriented programming in python.

Syntax of creating destructor:

#syntax of creating destructor

def __del()__(self):

#syntax of destructor

When destructor is called: There are two conditions when destructor is called:

1). When we want to delete object explicitly after execution of program. “del” keyword followed by object name is used to call destructor.
2). If any error or exception occur during initializing an object in init method. Then destructor is called automatically.

Note: After calling the destructor object is deleted completely. By object, we means the blue print of a class. So keep in mind, its the best practice to call the destructor at the end after completion of whole program.
Because if we call destructor first, it will delete our object and we are not able to perform any operation using that object.

Do not worry I will show you both examples by doing.

Example 1: In this example we will see the example in which we call the destructor at end, after the execution of all program.

#Parameterized Constructor

class Test:
    x = 24
    def __del__(self):     #Destructor definition
        print("Destructor called and class Test is deleted")
    
# c1 = Test()
c2 = Test()
print(c2.x)
del c2           #Destructor called

Output:

#Output
# 24
# Destructor called and class Test is deleted

Example 2: In this example we will see the example in which we call the destructor at start, before the execution of all program.

#Parameterized Constructor

class Test:
    x = 24
    def __del__(self):   #destructor definition
        print("Destructor called and class Test is deleted")
        
# c1 = Test()
c2 = Test()
del c2       #Destructor called
print(c2.x)

Output:

#Output
#Destructor called and class Test is deleted
#NameError: name 'c2' is not defined