Code Crafter IT Innovation
Loading...
  • Bansal Computer Center
  • punjabedu.bansalcenter.com

Python Destructors

What is a Destructor?

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.

Purpose of Destructor

Destructor is used to perform cleanup work, such as:

Method Name: __del__(self)

It has a fixed name __del__ and is automatically executed. It accepts no arguments except self.

Constructor vs Destructor

Understanding the difference between the creation and destruction phases of an object.

FeatureConstructorDestructor
Method__init__()__del__()
TriggerCalled on object creationCalled on object destruction
PurposeInitializes dataCleans up data/resources
OrderRuns firstRuns last

Implementation Examples

1. Simple Creation and Destruction

class Demo:
    def __init__(self):
        print("Object created")

    def __del__(self):
        print("Object destroyed")

d = Demo()
# Output:
# Object created
# Object destroyed (when program ends)

2. Using the 'del' Keyword

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__

3. Interaction with Normal Methods

class Test:
    def __init__(self):
        print("Constructor")
    def show(self):
        print("Normal method")
    def __del__(self):
        print("Destructor")

t = Test()
t.show()

Object Life Cycle

The journey of an object from start to finish in Python memory.

Garbage Collection

Python’s automatic memory management system (Garbage Collector) removes objects when their reference count hits 0, triggering the destructor.

Important Rules & Real-Life Usage

Rules to Follow:

Real-Life Example: File Handling

class FileHandler:
    def __init__(self):
        self.f = open("test.txt", "w")
        print("File opened")

    def __del__(self):
        self.f.close()
        print("File closed safely")

Quick Revision Summary

FeatureDestructor Details
Method name__del__()
Called whenObject is destroyed/Garbage collected
PurposeCleanup (Close files/Free RAM)
Manual callNo (Triggered by del or GC)

Exam One-Liners:

What students Say?

Here are the stdudents...

#

Contact Us

Empower your tech dreams with us. Get in touch!

  • #
  • #
  • #
  • #
  • #