- Using Multiple Arguments to Overload Constructors in Python
@classmethodDecorators to 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.
class delftstack: def __init__(self, *args): if isinstance(args, int): self.ans = args elif isinstance(args, str): self.ans = "Hello from "+args s1 = delftstack(1) print(s1.ans) s2 = delftstack("Delft") print(s2.ans)
1 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) print(s1.ans) s2 = delftstack(1,2) print(s2.ans)
More than three Less than three
@classmethod Decorators to Overload a Constructor in Python
@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' @classmethod def first(cls): return "first" @classmethod def second(cls): return "second" s1 = delftstack.first() print(s1) s2 = delftstack.second() print(s2)
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.