Constructor Overloading in Python

Posted by Afsal on 13-Nov-2021

Hello Pythonistas!

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

In Python, we can use two methods for constructor overloading:

  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.radius = args[0]
            self.name = "circle"
        elif len(args) == 2:
            print("square")
            self.length = args[0]
            self.breadth = args[1]
            self.name = "rectangle"

    def __str__(self):
           if self.name == "circle":
               return f'{self.name} with radius {self.radius}'
           else:
              return f'{self.name} with length={self.length} and breadth={self.breadth}'

 

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":
            return f'{self.name} with radius {self.radius}'
        else:
            return f'{self.name} with length={self.length} and breadth={self.breadth}'

    @classmethod
    def create_circle(cls, radius):
        obj = cls()
        obj.name = "circle"
        obj.radius = radius
        return obj

    @classmethod
    def create_rectangle(cls, length, breadth):
        obj = cls()
        obj.name = "rectangle"
        obj.length = length
        obj.breadth = breadth
        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.

I hope this tutorial was helpful. Please do share your thoughts and suggestions. 

If you have any topics in mind that can be discussed on our platform, please mail at afsal@parseltongue.co.in