Constructor in Python [Complete Guide]

When learning Object-Oriented Programming (OOP) in Python, one of the fundamental concepts to understand is the constructor. The constructor is a special method that is executed when an object is created from a class. In this post, we will dive into Python constructors, default constructors in Python, and constructor overriding in Python.

What is a Constructor in Python?

In Python, a constructor is a special method that initializes an object of a class. It’s the method that gets called when you create a new instance of a class. The name of this method is always __init__. The double underscores before and after the name signify that it’s a special method.

Syntax:

class ClassName:
    def __init__(self, [parameters]):
        # code to initialize the object

Here’s an example:

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

In this example, we have a simple Car class with a constructor that takes two parameters: brand and model.

Creating a new instance of the Car class:

my_car = Car("Toyota", "Corolla")
print(my_car.brand)  
print(my_car.model) 

You can check the output below:

Constructor in Python
Constructor in Python

Default Constructor in Python

A default constructor is a constructor that doesn’t take any parameters (except for self, which refers to the object itself). If you don’t define a constructor in your class, Python will automatically provide a default constructor that doesn’t do anything.

Here’s an example:

class Animal:
    pass

my_animal = Animal()

In this example, the Animal class doesn’t define a constructor, so Python provides a default one. You can create an instance of Animal without passing any parameters.

READ:  Priority queue in Python [3 Ways to implement]

Parameterized Constructor

If you want your constructor to accept parameters to initialize the object’s attributes, you can define a constructor with additional parameters.

Here’s an example:

class Circle:
    def __init__(self, radius):
        self.radius = radius
        
    def area(self):
        return 3.14 * self.radius * self.radius

my_circle = Circle(5)
print(my_circle.area())  # Output: 78.5

In the above example, the Circle class has a constructor that takes a parameter radius, and a method area to calculate the area of the circle.

Constructor Overriding in Python

In OOP, a subclass can provide a specific implementation of a method that is already defined in its superclass. This is known as method overriding. Constructor overriding is when a subclass provides its own implementation of the constructor.

Let’s look at an example:

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

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

person = Person("Alice")
employee = Employee("Bob", 123)

print(person.name)        
print(employee.name)     
print(employee.employee_id) 

In this example, the Employee class is a subclass of Person. The Employee class overrides the constructor of the Person class to accept an additional parameter employee_id. The super() function is used to call the constructor of the superclass (Person).

You can see the output in the below screenshot.

Constructor Overriding in Python
Constructor Overriding in Python

Conclusion

Understanding constructors is essential when working with classes and objects in Python. In this post, we explored the basics of constructors, including the default constructor provided by Python, how to define a parameterized constructor, and how to override constructors in subclasses.

You may like the following Python tutorials: