Constructor and Destructor

A constructor is a special method that runs automatically when a new object is created, typically used to initialize the object's starting attributes. A destructor is a special method that runs when an object is about to be destroyed, typically used for cleanup.

The Constructor: __init__

class Student:
    def __init__(self, name, course):
        print("Creating a new student object...")
        self.name = name
        self.course = course

s = Student("Abhay", "Data Science")

The __init__ method runs immediately whenever a new Student object is created, ensuring every object starts with its required data already set.

The Destructor: __del__

class Student:
    def __init__(self, name):
        self.name = name

    def __del__(self):
        print(f"Destroying student object: {self.name}")

s = Student("Abhay")
del s   # triggers __del__

The __del__ method runs when an object is explicitly deleted or when Python's garbage collector removes it because it's no longer referenced anywhere in the program.

Destructors are used far less often in Python than constructors, since Python's automatic garbage collection usually handles cleanup reliably without needing explicit intervention.

Coming Up Next

Next, you'll explore Decorators - a powerful Python feature for modifying or extending a function's behavior without changing its actual code.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course