Overload a Constructor in Python

  1. Using Multiple Arguments to Overload Constructors in Python
  2. Use the @classmethod Decorators to Overload a Constructor in Python
Overload a Constructor in Python

Multiple constructors help in customizing our custom class accordingly to its parameters. While using different parameters, we can trigger different constructors.

Multiple constructors are not directly supported in Python. When multiple constructors are provided in the class, the latest one overrides the previous one. But there are some alternative ways to overload a constructor in Python.

We will discuss these methods in this article.

Using Multiple Arguments to Overload Constructors in Python

Function overloading refers to having different functions with the same name with different types of parameters. We can overload a constructor by declaring multiple conditions, with every condition based on a different set of arguments.

For example,

class delftstack:
	def __init__(self, *args):
		if isinstance(args[0], int):
			self.ans = args[0]
		elif isinstance(args[0], str):
			self.ans = "Hello from "+args[0]

s1 = delftstack(1)

s2 = delftstack("Delft")


Hello from Delft

In the above example, we have two types of parameters in the constructor. One is a string, and the other is an integer. The construct is overloaded to give the output based on the type of arguments provided.

We can also overload a constructor based on the number of arguments provided. This method is similar to the previous example.

See the code below.

class delftstack:
	def __init__(self, *args):
		if len(args)>3:
			self.ans = "More than three"
		elif len(args)<=3:
			self.ans = "Less than three"

s1 = delftstack(1,2,3,4)

s2 = delftstack(1,2)


More than three

Less than three

Use the @classmethod Decorators to Overload a Constructor in Python

The @classmethod decorator allows the function to be accessible without instantiating a class. Such methods can be accessed by the class itself and via its instances. When used in overloading, such functions are called factory methods. We can use them to implement the concept of constructor overloading in Python.

See the code below.

class delftstack(object):
    def __init__(self, a):
        self.ans = 'a'
    def first(cls):
        return "first"

    def second(cls):
        return "second"

s1 = delftstack.first()


s2 = delftstack.second()





This method is the most pythonic way of overloading a constructor. In the above example, the cls argument of the factory method refers to the class itself.

Related Article - Python Constructor

  • Python Multiple Constructors