Method and Constructor Overloading in Python

In this class, we discuss the method and constructor overloading in python.

For Complete YouTube Video: Click Here

Method and Constructor Overloading

The reader should have prior knowledge of class, object, and method. Click here.

First, we have to understand the concept of method overloading.

Later we discuss the method overloading possible in python or not.

Take an example and understand the concept of method overloading.

class test:
    def __init__(self, k):
        self.x1=k
    def f(self,a):
        print("this is method")
        print(self.x1)
    def f(self,a,b):
        print(self.x1+a)
ob1=test(1)
ob1.f(5)

In the above program, we have a method f with one parameter and another method with the same name f and with two parameters.

Two methods in a class have the same name we call method overloading.

Both the methods are having different signatures. Signature means a different number of parameters.

If the constructor is written two times with different signatures, we call constructor overloading.

The concept of method overloading and constructor overloading is possible in other languages like java and c++.

In the python method and constructor, overloading is not possible.

Calling overloaded methods are shown in the above program.

x.f(10) and x.f(10,20) call the methods separately based on the signature. this is done in other languages.

Take an example in python and understand how method overloading and constructor overloading works.

# constructor and method overloading
class test:
    def __init__(self, k):
        self.x1=k
    def __init__(self,l,k):
        self.x1=l
        self.x2=k
    def f(self):
        print("this is method")
        print(self.x1+self.x2)
ob1=test(1,5)
ob1.f()

In the above program, the constructor is overloaded. Python considers the last defined constructor into consideration.

Python interpreter does not consider the first constructor.

In The above program, we created an object with two parameters passed. Those two parameters are passed to the second constructor.

If we define the object with a single parameter, we get an error. Python does not consider the first constructor.

The example is given below.

class test:
    def __init__(self, k):
        self.x1=k
    def __init__(self,l,k):
        self.x1=l
        self.x2=k
    def f(self):
        print("this is method")
        print(self.x1+self.x2)
ob1=test(1)
ob1.f()

error : missing 1 required positional argument: 'k'

Similarly, method overloading also works. The examples are shown below.

class test:
    def __init__(self, k):
        self.x1=k
    def f(self):
        print("this is method")
        print(self.x1)
    def f(self,a):
        print(self.x1+a)
ob1=test(1)
ob1.f(5)

Output:
6