Explain Method Overloading In Python With Example

Hi Guys, welcome to my blog in this article you will learn about how to Explain Method Overloading In Python With Example

 

Title : 

Explain Method Overloading In Python With Example



Explain Method Overloading In Python With Example


 

Description : 

Hey guys in this article you will learn about how to overload a function in python. You can perform function overloading using the below two methods Using default arguments Using unpacking arguments / keyword arguments (*args and **kwargs) Lets look into default function arguments Declare a function named as add() and pass two input arguments (a & b) to it, also pass the third argument (c) by initialising it to zero. Usage : You can call add() function with the two or three arguments as shown below.


    
def add(a, b, c=0):
   return a + b + c

print(add(1,2))
print(add(1,2,3))

    


Let's look into second method of overloading using unpacking arguments / keyword args Take the above add function and define the argument as *args will be unpacked later. take the total variable and initialize it to zero it rate all the values present in the argos and added to the total variable finally return the total. Now in the main program call the and function by passing to and three values, print the result


    
def add(*args):
   total = 0
   for item in args:
       total += item
   return total

print(add(1,2))
print(add(1,2,3))


    


Now take the keyword arguments as input to the add function **kwargs, and iterate the key value pairs and at the value to the total variable. Finally return the total variable as output of the function. In the main program pass the key value pairs first and second. and in the next function call pass the first, second and third variables as input.


    
def add(**kwargs):
   total = 0
   for key, value in kwargs.items():
       total += value
   return total

print(add(first=1, second=2))
print(add(first=1, second=2, third=3))


    




Complete Python Code : 


    
Program #1
def add(a, b, c=0):
   return a + b + c

print(add(1,2))
print(add(1,2,3))


Program #2
def add(*args):
   total = 0
   for item in args:
       total += item
   return total

print(add(1,2))
print(add(1,2,3))


Program #3
def add(**kwargs):
   total = 0
   for key, value in kwargs.items():
       total += value
   return total

print(add(first=1, second=2))
print(add(first=1, second=2, third=3))

    

 

 

Output : 


    
3
6


    

 

Output : 


    

    



Conclusion :

The above Python program defines the add() function to pass 2 and 3 input arguments and then compute the result. There are three variants of the method overloading programs first using default arguments, second using unpacking the arguments and finally third using the keyword arguments Comment it down below if you have any suggestions to improve the above Python program

 

Post a Comment

0 Comments