Destructor in python
What are Destructor in python ?
Destructor is called when an object gets destroyed. In Python, destructors are not needed, because Python has a garbage collector that handles memory management automatically.
The __del__() method is known as a destructor method.
Example:
- class ClassName:
- def __del__(self):
Function of Destructor in Python:
- 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 for Destructor in Python:
#python Program
#Rishikesh
#destructor
class A(object):
def __init__(self):
self.str1 = “PrepInsta”
print(“Object Created” , self.str1)
def __del__(self):
print(‘DEstructor is called automatically’)
ob = A()
Output:
Object Created PrepInsta
DEstructor is called automatically
- The destructor was called after the program ended.
- It was called Automatically.
- Object will be deleted at the end of the program.
Code #2 :
#python Program
#Rishikesh
#destructor
class A(object):
def __init__(self):
self.str1 = “PrepInsta”
print(“Object Created” , self.str1)
def __del__(self):
print(‘DEstructor is called Manually’)
ob = A()
del ob
#ob1=A()
#destructor will be called automattically for ob1
Output:
Object Created PrepInsta
DEstructor is called Manually
Login/Signup to comment