Python | Method Overloading - GeeksforGeeks

19 Feb, 2021
Like other languages (for example, method overloading in C++) do, python does not support method overloading by default. But there are different ways to achieve method overloading in Python. 
The problem with method overloading in Python is that we may overload the methods but can only use the latest defined method. 
Python3
# First product method.# Takes two argument and print their# productdef product(a, b):    p = a * b    print(p)      # Second product method# Takes three argument and print their# productdef product(a, b, c):    p = a * b*c    print(p)  # Uncommenting the below line shows an error    # product(4, 5)  # This line will call the second product methodproduct(4, 5, 5)
Output: 
100
In the above code, we have defined two product method, but we can only use the second product method, as python does not support method overloading. We may define many methods of the same name and different arguments, but we can only use the latest defined method. Calling the other method will produce an error. Like here calling will produce an error as the latest defined product method takes three arguments.
Thus, to overcome the above problem we can use different ways to achieve the method overloading.
Method 1 (Not The Most Efficient Method):We can use the arguments to make the same function work differently i.e. as per the arguments.
Python3
# Function to take multiple argumentsdef add(datatype, *args):      # if datatype is int    # initialize answer as 0    if datatype =='int':        answer = 0              # if datatype is str    # initialize answer as ''    if datatype =='str':        answer =''      # Traverse through the arguments    for x in args:          # This will do addition if the         # arguments are int. Or concatenation         # if the arguments are str        answer = answer + x      print(answer)  # Integeradd('int', 5, 6)  # Stringadd('str', 'Hi ', 'Geeks')
Output: 
11
Hi Geeks
The problem with above code is that makes code more complex with multiple if/else statement and is not the desired way to achieve the method overloading.
Method 2 (Efficient One):By Using Multiple Dispatch Decorator Multiple Dispatch Decorator Can be installed by: 
pip3 install multipledispatch
Python3
from multipledispatch import dispatch  #passing one parameter@dispatch(int,int)def product(first,second):    result = first*second    print(result);  #passing two parameters@dispatch(int,int,int)def product(first,second,third):    result  = first * second * third    print(result);  #you can also pass data type of any value as per requirement@dispatch(float,float,float)def product(first,second,third):    result  = first * second * third    print(result);    #calling product method with 2 argumentsproduct(2,3,2) #this will give output of 12product(2.2,3.4,2.3) # this will give output of 17.985999999999997
Output: 
12
17.985999999999997
In Backend, Dispatcher creates an object which stores different implementation and on runtime, it selects the appropriate method as the type and number of parameters passed. 
YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Method Overloading | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=jMQfA1cmFw8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Vidip
shahid211099
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python
How To Convert Python Dictionary To JSON?