Learn Python Programming

Python – Method Overloading


When more than one method with the same name is defined in the same class, is know as method overloading.

Unlike C++, Java etc., Python does not support method overloading. However you may overload the methods but can only use the latest defined method.

Let us understand with an example.

class Calculation:
    def product(self, a,b):
        p = a*b
        print(p)

    def product(self, a,b,c):
        p = a*b*c
        print(p)


obj = Calculation()
print(obj.product(3,3,5))

#OUTPUT
45

In the above example, you see only the latest defined method of same method name is automatically used.

What will happen if you change the parameters in latest product method. You will get an error because in recent ‘product’ method you have to pass 3 positional arguments requested in ‘product’ function.

class Calculation:
    def product(self, a,b):
        p = a*b
        print(p)

    def product(self, a,b):
        p = a*b*c
        print(p)


obj = Calculation()
print(obj.product(3,3,5))

#OUTPUT
Traceback (most recent call last):
  File "method_overloading.py", line 12, in <module>
    print(obj.product(3,3,5))
TypeError: product() takes 3 positional arguments but 4 were given