Overloading constructors in Python

Python Constructor is a part of Object-Oriented Programming in Python which is a special kind of method/function. It is used to intialize instance members of that class.

It is also used to ensure that we have enough resources. If we want to create an object of that class , then constructor definition is the first to execute.

Constructor are used for instantiating an object.Its task is to assign values to the data member of a particular class when the object of that class is created.

__init__() method is called constructor and is called when an object is created.

Here Constructor Overloading means more than one constructor is present in a class with the same name but with a different arguments.

In Python Construction Overloading is not supported: 

Example:

In this example we will see that if we give it more than one constructor, that does not do constructor overloading in Python.

class abc:
    def __init__(self):
            print("Hello World")
    def __init__(self):
            print("Welcome to Python")
a=abc()

Output: Welcome to Python

In this example, we have used default arguments to overload a constructor.

class abc:
    def __init__(self, nam=None):
        if nam:
            print("Hello", nam)
        else:
            print("Default Constructor")

obj1 =abc("John")
obj2 =abc()

Output:

Hello John
Default Constructor
Tags