Python Method Overloading
If a method is written such that it can perform more than one task, it is called method overloading.
Method Overloading
We see method overloading in the languages like Java. For example, we call a method as:
sum(10, 15)
sum(10, 15, 20)
In the first call, we are passing two arguments and in the second call, we are passing three arguments. It means, the sum() method is performing two distinct operations: finding sum of two numbers or sum of three numbers.This is called method overloading.
Method Overloading Example
Copied
#method overloading
class Myclass:
def sum(self, a=None, b=None, c=None):
if a!=None and b!=None and c!=None:
print('Sum of three=', a+b+c)
elif a!=None and b!=None:
print('Sum of two=', a+b)
else:
print('Please enter two or three arguments')
#call sum() using object
m = Myclass()
m.sum(10, 15, 20)
m.sum(10.5, 25.55)
m.sum(100)
Here the sum() method is calculating sum of two or three numbers and hence it is performing more than one task. Hence it is an overloaded method. In this way, overloaded methods achieve polymorphism.