Posted by Afsal on Nov. 13, 2021, 5:02 a.m.

Hello Pythonistas!

Today we are going to discuss a simple topic, i.e., Constructor Overloading in Python.

1. Using *args in __init__ method
2. Using @classmethod

Let’s look at the methods in detail.

Using *args in __init__

This is a very simple method. We use a variable number of positional arguments and write conditions according to that. Consider the following example.

``````class Shape:

def __init__(self, *args):
if len(args) == 1:
print("circle")
self.name = "circle"
elif len(args) == 2:
print("square")
self.length = args
self.name = "rectangle"

def __str__(self):
if self.name == "circle":
else:
``````

``````a = Shape(1)
print(a)``````
``circle with radius 1``
``````b = Shape(2, 3)
print(b)
``````
``rectangle with length=2 and breadth=3``

The limitation to this approach is that if we need to add a new shape, we have to update the __init__ method again. The next method, @staticmethod, is a solution to this problem.

Using @classmethod

As Python developers, we always wonder when to use @classmethod. This can be used for a clean implementation of constructor overloading.

``````class Shape:
def __str__(self):
if self.name == "circle":
else:

@classmethod
obj = cls()
obj.name = "circle"
return obj

@classmethod
obj = cls()
obj.name = "rectangle"
obj.length = length
return obj
``````
``````a = Shape.create_circle(1)
print(a)
``````
``circle with radius 1``
``````b = Shape.create_rectangle(2, 3)
print(b)``````
``rectangle with length=2 and breadth=3``

This code is more simple and readable than the previous one. Another positive is that we can extend it easily without repeating the code again.