Python Guide Sidebar

Python – Constructors

Introduction to Constructors in Python

In Python, a constructors is a special method used to initialize an object when it is created. It allows you to define default values for instance attributes and execute specific code automatically during object instantiation. The constructor method in Python is called __init__(), and it is executed whenever a new object of the class is created.

Why Use Constructors?

  • Automatically initializes object attributes when an object is created.
  • Reduces code duplication by setting default values in a single place.
  • Enhances code readability and organization.
  • Allows parameterized object creation for better flexibility.

Types of Constructors in Python

Python supports three types of constructors:

1. Default Constructor (No Arguments)

A default constructor does not take any parameters (except self). It initializes object attributes with predefined values.

Example:
class Car:
    def __init__(self):  # Default constructor
        print("A new car has been created!")

# Creating an object
car1 = Car()  
Output:
A new car has been created!

2. Parameterized Constructor

A parameterized constructor accepts arguments and assigns them to instance variables during object creation.

Example:
class Car:
    def __init__(self, brand, model):  # Parameterized constructor
        self.brand = brand
        self.model = model

    def show_details(self):
        print(f"Car Brand: {self.brand}, Model: {self.model}")

# Creating objects with parameters
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Civic")

car1.show_details()
car2.show_details()

Output:

Car Brand: Toyota, Model: Camry
Car Brand: Honda, Model: Civic

3. Constructor with Default Arguments

You can define a constructor with default argument values, making some parameters optional during object creation.

Example:

class Car:
    def __init__(self, brand="Unknown", model="Unknown"):
        self.brand = brand
        self.model = model

    def show_details(self):
        print(f"Car Brand: {self.brand}, Model: {self.model}")

# Creating objects with and without arguments
car1 = Car("Ford", "Mustang")
car2 = Car()

car1.show_details()
car2.show_details()

Output:

Car Brand: Ford, Model: Mustang
Car Brand: Unknown, Model: Unknown

Using None as a Default Argument in Constructors

Sometimes, a constructor can accept optional arguments and assign None if a value is not provided.

Example:

class Student:
    def __init__(self, name, age=None):
        self.name = name
        self.age = age if age is not None else "Not Provided"

    def show_info(self):
        print(f"Student Name: {self.name}, Age: {self.age}")

# Creating objects with and without providing age
s1 = Student("Alice", 20)
s2 = Student("Bob")

s1.show_info()
s2.show_info()

Output:

Student Name: Alice, Age: 20
Student Name: Bob, Age: Not Provided

Using super() to Call Parent Class Constructor

In Python, if a class inherits from another class, you can use super() to call the parent class’s constructor.

Example:

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

    def show_name(self):
        print(f"Name: {self.name}")

class Employee(Person):
    def __init__(self, name, emp_id):
        super().__init__(name)  # Calling the parent class constructor
        self.emp_id = emp_id

    def show_details(self):
        print(f"Name: {self.name}, Employee ID: {self.emp_id}")

# Creating an object of Employee
e1 = Employee("John Doe", 101)
e1.show_details()

Output:

Name: John Doe, Employee ID: 101

Destructor in Python (__del__() Method)

Python also provides a special method called destructor (__del__()) that is executed when an object is deleted.

Example:

class Test:
    def __init__(self, value):
        self.value = value
        print(f"Object {self.value} is created.")

    def __del__(self):
        print(f"Object {self.value} is deleted.")

# Creating an object
obj = Test(10)

# Deleting the object manually
del obj

Output:

Object 10 is created.
Object 10 is deleted.

Key Takeaways

  • Constructors (__init__()) initialize an object’s attributes at the time of object creation.
  • They can be default (without parameters) or parameterized (with arguments).
  • Constructors with default values allow flexibility in object creation.
  • super() helps in calling a parent class’s constructor in inheritance.
  • Destructors (__del__()) handle cleanup tasks when an object is deleted.

Conclusion

Constructors in Python provide a structured way to initialize objects automatically. They help set default values, ensure data consistency, and improve code readability. Understanding different types of constructors, including default, parameterized, and those with default arguments, allows for better object management. Additionally, destructors handle object cleanup, making memory management more efficient. By using constructors effectively, you can write clean, reusable, and maintainable object-oriented programs.

Additional Resources