Skip to content

Constructor overloading in Python | Example code

  • by

Constructor overloading means more than one constructor in a class with the same name but a different argument (parameter). Python does not support Constructor overloading; it has no form of function.

In Python, Methods are defined solely by their name, and there can be only one method per class with a given name.

Example constructor overloading in Python

Simple example code to achieve constructor overloading based on args.

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 :", e1.answer)

e2 = Example(6)
print("Square :", e2.answer)

e3 = Example("Python")
print("String :", e3.answer)


Constructor overloading in Python

Constructor overloading in python with default arguments

Python does not support multiple constructors. However, you can emulate them easily as follows:

class MyClass:
    def __init__(self, edate=None, fdate=""):
        if edate:
            print("Constructors", edate)
            print("Default Constructor")

obj1 = MyClass("01-Dec-2021")

obj2 = MyClass()


Constructors 01-Dec-2021
Default Constructor

How to overload __init__ method based on argument type?

Answer: Do get ‘alternate constructors’ is to use classmethods. For instance:

class MyData:
    def __init__(self, data): = data

    def fromfilename(cls, filename):
        data = open(filename).readlines()
        return cls(data)

    def fromdict(cls, datadict):
        MyData([1, 2, 3]).data
        return cls(datadict.items())


print(MyData.fromdict({"spam": "ham"}).data)


[‘Welcome Developer’]
dict_items([(‘spam’, ‘ham’)])


Do comment if you have any doubts or suggestions on this Python constructor 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 *