Python | Method overloading

Python Methods and Functions

# First product method.
# Takes two arguments and prints them
# product

def product (a, b):

p = a * b

  print (p)

  
# Second product method
# Takes three arguments and prints them
# product

def product (a, b , c):

  p = a * b * c

print (p)

 
# Uncommenting the line below shows an error
# product (4, 5)

 
# This line will call the second product method

product ( 4 , 5 , 5 )

Output:

 100 

In the above code, we have defined two and the product method, but we can only use the second product method since python does not support method overloading. We can define many methods with the same name and different argument, but we can only use the last defined method. Calling another method will result in an error. As the name here is will throw an error because the last defined method of the product takes three arguments.

However, we can use a different implementation in python to make the same function work differently, that is, according to the arguments.

# Function to get multiple arguments

def add (datatype, * args):

  

  # if data type is int

# initialize response as 0

if dataty pe = = 'int' :

answer = 0

 

  # if the data type is str

  # initialize response as & # 39; & # 39;

  if datatype = = ' str' :

answer = ''

 

< code class = "comments"> # Step through the arguments

for x in args:

  

  # The addon will do this if

# int arguments. Or concatenation

# if str arguments

answer = answer + x

 

print (answer)

 
# Integer

add ( 'int' , 5 , 6 )

  
# String

add ( 'str' , ' Hi ' , ' Geeks' )

Output:

 11 Hi Geeks 




Tutorials