In Python, you can’t define multiple constructors. However, you can define a default value if one is not passed.
def __init__(self, city="Berlin"): self.city = city
Way to Achieve Multiple Constructors in Python
Multiple constructors come to use when a defined class has to perform different functions. You can do Python Constructor overloading based on arguments as Multiple Constructors.
Do if-elif blocks based on the type:
class Example: # constructor overloading based on args def __init__(self, *args): # if args are more than 1 sum of args if len(args) > 1: self.answer = 0 for i in args: self.answer += i # if arg is an integer square the arg elif isinstance(args, int): self.answer = args * args # if arg is string Print with hello elif isinstance(args, str): self.answer = "Hello! " + args + "." e1 = Example(1, 2, 3, 6, 8) print("Sum of list :", e1.answer) e2 = Example(6) print("Square of integer :", e2.answer) e3 = Example("Programmers") print("String :", e3.answer)
Do comment if you have any doubts and suggestions on this Python constructors tutorial.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.