Skip to content

Python multiple constructors | Example code

  • by

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[0], int):
            self.answer = args[0] * args[0]

        # if arg is string Print with hello
        elif isinstance(args[0], str):
            self.answer = "Hello! " + args[0] + "."


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)

Output:

Python multiple constructors
Python multiple constructors

Do comment if you have any doubts or suggestions on this Python constructors tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *