Python | Method Overloading

Like other languages (for example method overloading in C++) do, python does not supports method overloading. We may overload the methods but can only use the latest defined method.

filter_none

edit
close

play_arrow

link
brightness_4
code

# First product method.
# Takes two argument and print their
# product
def product(a, b):
    p = a * b
    print(p)
      
# Second product method
# Takes three argument and print their
# product
def 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 method
product(4, 5, 5)

chevron_right


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 supports method overloading. We may define many method of same name and different argument but we can only use the latest defined method. Calling the other method will produce an error. Like here calling product(4, 5) will produce an error as the latest defined product method takes three arguments.



However we may use other implementation in python to make the same function work differently i.e. as per the arguments.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Function to take multiple arguments
def 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)
  
# Integer
add('int', 5, 6)
  
# String
add('str', 'Hi ', 'Geeks')

chevron_right


Output:

11
Hi Geeks



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

5


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.