__del__() in python

__del__() in Python 

Whenever we listen class, object or Opps one thing comes to our mind is destructor if we know basic of c++. In this article, we will discuss __del__() in Python, its usages and many more things. If you are familiar with c++, you might have the idea of destructor, __del__ method is the destructor in python. 

Let’s understand the function of __del__() in Python.

__del__ in python

Function of __del__:

  • The __del__ method is similar to destructor in c++ and Java.
  • Destructors are used to destroying the object’s state. 

Syntax:

class ClassName:
def __del__( self ,):
##body

Code #1:


#python Program
#Rishikesh 
#destructor
#__del__
 
class A(object): 
    def __init__(self): 
        self.str1 = “PrepInsta”
        print(“Object Created” , self.str1) 
    def __del__(self):
        print(‘Del is called’)
        

ob = A() 

Output: 

Object Created PrepInsta
Del is called
__del__ () in Python

Code #2:


#python Program
#Rishikesh 
#destructor
 
class A(object): 
    def __init__(self): 
        self.str1 = “PrepInsta”
        print(“Object Created” , self.str1) 
    def __del__(self):
        print(‘Del is called manually’)
        

ob = A() 
del A

Output:

Object Created PrepInsta
Del is called manually