Constructor in Python


What is Constructor

A constructor is a special method that is used to initialize the data members of the class. The constructor is called automatically when the object of the class is created.

The constructor cannot return any value.

Constructor

Syntax:

In [ ]:
def __init__(self):
    #body

Here, we use the __init__() Method to define the constructor. It is the special method, that is called automatically, when an object of the class is created.

We pass self as the first argument, which acts as the instance of the class.

Example

In [1]:
class car:
    def __init__(self):
        print("Inside init.")

Constructor getting called automatically when object is created.

In [2]:
model_3 = car()
model_S = car()
Inside init.
Inside init.

Types of Constructor

In python, we have three types of constructor:

  1. Default Constructor
  2. Non-parameterized constructor
  3. Parameterized constructor

Default Constructor

Python will automatically create a constructor when we do not define any constructor of the class. This constructor is known as the default constructor.

It is used to initialize the objects of the class. It is an empty constructor without a body.

Example:

In this example, we do not have any constructor, but still, we can create the object of the class and call the member function using the default constructor.

In [1]:
class car:
    def say_Hello(self):
        print("Hello, How are you?")

Default constructor is used to create the object of the class.

In [2]:
model_3 = car()

Calling function say_Hello.

In [3]:
model_3.say_Hello()
Hello, How are you?

Non-Parameterized Constructor

A constructor, that does not have any argument, is known as the non-parameterized constructor. It is used to initialize objects with the default values. These values will be similar across all the objects of the class.

Example:

In [1]:
class car:
    def __init__(self):
        self.company_name = "Tesla"
        self.company_owner = "Elon Musk"

Creating Object.

In [2]:
model_3 = car()

Accessing member variables.

In [3]:
print(model_3.company_name)
print(model_3.company_owner)
Tesla
Elon Musk

Parameterized Constructor

Parameterized constructor is the constructor that accepts arguments. This type of constructor is used when we want to initialize each object with a different value.

Take care, the first parameter is always self.

Example:

In [1]:
class car:
    def __init__(self, car_type, seating_capacity):
        self.car_type = car_type
        self.seating_capacity = seating_capacity

Passing parameters while creating objects.

In [2]:
model_3 = car("Sedan",5)
model_X = car("SUV",5)

Accessing car_type variable of both objects.

In [3]:
print(model_3.car_type)
print(model_X.car_type)
Sedan
SUV

Advantages of Constructors in Python

1. Object Initialization: Constructors ensure that objects are properly initialized when they are created. The __init__ method is automatically called when an object is instantiated, allowing you to perform any necessary setup.

2. Code Reusability: Like in other object-oriented languages, constructors in Python promote code reusability. The initialization logic is encapsulated within the constructor, and it can be reused every time an object of that class is created.

3. Parameterized Initialization: Python constructors support parameterized initialization, allowing you to pass values during object creation. This provides flexibility in initializing objects with different initial states.

4. Default Values: Constructors can define default values for parameters, providing a way to initialize objects without explicitly specifying all the values.

5. Encapsulation: Constructors are part of the encapsulation mechanism in Python, helping in bundling data (attributes) and methods together within a class.

Disadvantages of Constructors in Python

1. Complexity: If the initialization logic becomes complex, the constructor may become lengthy and harder to understand. This can impact code readability and maintainability.

2. Limited Flexibility: Python’s __init__ method allows for parameterized initialization, but it may not cover all possible scenarios. In some cases, you might need additional methods to handle more complex initialization.

3. Inability to Return Values: Similar to other programming languages, Python constructors cannot return values. If there’s a need to perform computations during object initialization and return a result, constructors may not be suitable.

4. Inheritance Complexity: Inheritance in Python can introduce complexities related to constructor execution order and initialization of base class components. Understanding the method resolution order (MRO) is crucial in such cases.

References:

  1. Default Constructor
  2. What is a constructor in Python?