How to Overload Constructor in Python?

Python Tutorials

The constructor method (i.e __init__) is used to instantiate an object of the class. It assigns values to the properties of an object when it is created.

Overloading the constructor in Python allows a class to be instantiated with different numbers and types of parameters per instance.

The following are the two ways to overload a constructor in Python.

Use Default Arguments To Overload Constructor

When you define the __init__ method with default arguments ex. def __init__(self, name=None), where name is the parameter with a default value of None, passing values for such parameters becomes optional.

This makes the constructor more dynamic and allows to create objects with flexible arguments.

class Car:
    def __init__(self, name, maxSpeed=None):
        self.name = name
        self.maxSpeed = maxSpeed
        

print(Car('Lamborghini v12', 300).__dict__)

print(Car('Ferrari 488').__dict__)

Output:

{‘name’: ‘Lamborghini v12’, ‘maxSpeed’: 300}
{‘name’: ‘Ferrari 488’, ‘maxSpeed’: None}

Use Starred and Keyword Arguments To Overload Constructor

If you define a funtion with single and double starred parameters ex. def func(*args, **kwargs), it can accepts any number of arguments.

Using the starred parameters in the __init__ method, you can easily overload the constructor with any number of arguments.

class Car:
    def __init__(self, *args, **kwargs):
        self.name = args[0]
        self.maxSpeed = kwargs.get('maxSpeed', None)
        self.engine = kwargs.get('engine', None)
        

print(Car('Lamborghini v12', engine='v12').__dict__)

print(Car('Ferrari 488', maxSpeed=280, engine='v8').__dict__)

Output:

{‘engine’: ‘v12’, ‘name’: ‘Lamborghini v12’, ‘maxSpeed’: None}
{‘engine’: ‘v8’, ‘name’: ‘Ferrari 488’, ‘maxSpeed’: 280}

*args is used to accept non-keyword arguments whereas, **kwargs is used to accept keyword arguments.

Leave a Reply

Your email address will not be published. Required fields are marked *