What students Say?
Here are the stdudents...
A destructor is a special method in Python that is automatically called when an object is destroyed.
Simple words: Object ke khatam hone par chalne wala function.Destructor is used to perform cleanup work, such as:
__del__(self)It has a fixed name __del__ and is automatically executed. It accepts no arguments except self.
Understanding the difference between the creation and destruction phases of an object.
| Feature | Constructor | Destructor |
|---|---|---|
| Method | __init__() | __del__() |
| Trigger | Called on object creation | Called on object destruction |
| Purpose | Initializes data | Cleans up data/resources |
| Order | Runs first | Runs last |
class Demo:
def __init__(self):
print("Object created")
def __del__(self):
print("Object destroyed")
d = Demo()
# Output:
# Object created
# Object destroyed (when program ends)
You can force a destructor to run by explicitly deleting the object reference.
class Sample:
def __init__(self):
print("Created")
def __del__(self):
print("Destroyed")
s = Sample()
del s # Explicitly triggers __del__
class Test:
def __init__(self):
print("Constructor")
def show(self):
print("Normal method")
def __del__(self):
print("Destructor")
t = Test()
t.show()
The journey of an object from start to finish in Python memory.
__init__ called)__del__ called)Python’s automatic memory management system (Garbage Collector) removes objects when their reference count hits 0, triggering the destructor.
class FileHandler:
def __init__(self):
self.f = open("test.txt", "w")
print("File opened")
def __del__(self):
self.f.close()
print("File closed safely")
| Feature | Destructor Details |
|---|---|
| Method name | __del__() |
| Called when | Object is destroyed/Garbage collected |
| Purpose | Cleanup (Close files/Free RAM) |
| Manual call | No (Triggered by del or GC) |
Here are the stdudents...
Empower your tech dreams with us. Get in touch!




