Constructors (__init__) and Destructors

What is a Constructor?

A constructor is a special method in a class that gets called automatically when a new object is created. In Python, the constructor method is __init__().

Defining a Constructor in Python

The __init__() method is used to initialize an object’s attributes when it is created.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Creating an object
person1 = Person("Ankit", 25)
person1.greet()  # Output: Hello, my name is Ankit and I am 25 years old.

How the Constructor Works

  1. When person1 = Person("Ankit", 25) is executed:
    • __init__() is called automatically.
    • "Ankit" and 25 are assigned to self.name and self.age.
    • The object person1 is now initialized with these values.

Types of Constructors in Python

Python supports three types of constructors:

1 . Default Constructor (No Parameters except self)

  • A constructor that does not take any arguments except self.
class Example:
    def __init__(self):
        print("Default constructor called")

obj = Example()  # Output: Default constructor called

2. Parameterized Constructor

  • A constructor that takes arguments to initialize an object’s attributes.
class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

car1 = Car("Tesla", "Model S")
print(car1.brand, car1.model)  # Output: Tesla Model S

3. Constructor with Default Values

  • You can assign default values to constructor parameters.
class Laptop:
    def __init__(self, brand="Dell"):
        self.brand = brand

l1 = Laptop()
l2 = Laptop("HP")

print(l1.brand)  # Output: Dell
print(l2.brand)  # Output: HP

What is a Destructor?

A destructor is a special method that is called when an object is deleted or goes out of scope. In Python, the destructor method is __del__().

Defining a Destructor in Python

class Student:
    def __init__(self, name):
        self.name = name
        print(f"Student {self.name} created!")

    def __del__(self):
        print(f"Student {self.name} is being deleted.")

# Creating an object
s1 = Student("Vivek")

# Deleting the object manually
del s1  # Output: Student Vivek is being deleted.

When is the Destructor Called?

  • It is called automatically when an object is no longer in use.
  • If the object is explicitly deleted using del, the destructor is executed immediately.
  • If an object goes out of scope (e.g., at the end of a function), the destructor is called.
def create_student():
    s2 = Student("Akash")
    print("Inside function")

create_student()
print("Outside function")

# Output:
# Student Akash created!
# Inside function
# Student Emma is being deleted.
# Outside function

Summary

The constructor (__init__()) is called when an object is created.
Types of constructors: Default, Parameterized, and with Default Values.
The destructor (__del__()) is called when an object is deleted or goes out of scope.