Understanding Method Overloading in Python




In this post, we will see how we can use method overloading in Python

What is method overloading?

It is a technique of using the same function name multiple times.

Example

Let's see method overloading in action.

# Func1
def add(a,b):
  print(a+b)
# Func2
def add(a,b,c):
  print(a+b+c)
  
# Uncommenting the below lines gives an error
# add(1,2)
add(1,2,3)

Output:

6

Python doesn't support method overloading by default. This means the function which is created at last will always override the previous definitions.
In above example, The add() with 3 arguments will override the add() with 2 arguments.

How we can use method overloading then?

To use the method overloading in Python, follow the below process.

  • Install Multiple Dispatch Decorator
pip3 install multipledispatch
  • Now you can use the decorator
from multipledispatch import dispatch 

#passing one parameter 
@dispatch(int,int) 
def add(a,b): 
	print(a+b); 

#passing two parameters 
@dispatch(int,int,int) 
def add(a,b,c): 
	print(a+b+c); 

add(2,3) #this will output 5
add(2,3,4) # this will output 9 

Check Output Here