Destructors
Destructors are called when an object gets destroyed. In Python, destructors are not needed as much needed in C++ because Python has a garbage collector that handles memory management automatically. The __del__() method is a known as a destructor method in Python. It is called when all references to the object have been deleted i.e when an object is garbage collected.
Example 1:
# Python program to illustrate destructor
class Employee:
# Initializing
def __init__(self):
print('Employee created.')
# Deleting (Calling destructor)
def __del__(self):
print('Destructor called, Employee deleted.')
obj = Employee()
del obj
Employee created.
Destructor called, Employee deleted.
Example 2:
# Python program to illustrate destructor
class Employee:
# Initializing
def __init__(self):
print('Employee created')
# Calling destructor
def __del__(self):
print("Destructor called")
def Create_obj():
print('Making Object...')
obj = Employee()
print('function end...')
return obj
print('Calling Create_obj() function...')
obj = Create_obj()
del obj
print('Program End...')
Calling Create_obj() function...
Making Object...
Employee created function end...
Destructor called
Program End...
Last updated
Was this helpful?