Method Overloading in Python (Simple Explanation With Example)
Method Overloading
How do you achieve method overloading in python?
We can not write two methods with same in python, even if you write , all previous method will be replaced with last method. Means whatever logic you write in last method that logic will run only.
Then how do you achieve method overloading in python?
We achvie MO using default positional argument, arbitrary argument(*args) keyword argument (**kwargs)
Example of using default Positional argument
We achieve method overloading in python using default parameter, so method will be only one, that will take n number of parameters , we will set default value for those parameters,
def add(×=0,y=0,z=0):
return x+y+z
add()
add(10,20)
add(10,20,30)
#Just one add funtion is handling 3 conditions,
#1. calling add() with No parameter, two parameters, and Three Parameters
# similarly we car overload the add with *agrgs and **kwargs
class Calculator:
def add(self, *args): # value received in form of tuple(1,2,3..)
if len(args) == 2:
return args[0] + args[1]
elif len(args) == 3:
return args[0] + args[1] + args[2]
else:
return sum(args)
def multiply(self, **kwargs): #value received in form of dict kwargs{x:2, y:3}
if 'x' in kwargs and 'y' in kwargs:
return kwargs['x'] * kwargs['y']
elif 'x' in kwargs and 'y' in kwargs and 'z' in kwargs:
return kwargs['x'] * kwargs['y'] * kwargs['z']
else:
return None
# Create an instance of the Calculator class
calculator = Calculator()
# Method overloading with variable-length arguments
result1 = calculator.add(1, 2) # Result: 3
result2 = calculator.add(1, 2, 3) # Result: 6
result3 = calculator.add(1, 2, 3, 4, 5) # Result: 15
# Method overloading with variable-length keyword arguments
result4 = calculator.multiply(x=2, y=3) # Result: 6
result5 = calculator.multiply(x=2, y=3, z=4) # Result: 24
print(result1, result2, result3, result4, result5)
And when we call that method with by sending different different parameter values, some parameter values we don’t send, what ever we don’t send, it will take default parameter value, and will execute and give the result according to the provided parameter value and default parameter value.
Constructor Overloading
Defining multiple constructor in single class with same name and default parameter, args, *kwargs. Its behave same as method overloading. One constructor will do multiple task
Operator Overloading
Python supports operator overloading, there is one magic method behind all the operetors, when we use any operator, internaly python invokes its related magic method.
By modifying its magic method, we can change the behavior of its operator. For example: ‘+’ operator , magic method is add(self)
When we give : a = 4+5 , add() method is executed. If we modify this add() method. Then ‘+’ operator behvaious will change as per our definition. This operator will no longer add any integer, it will work only according to our definition.