Go Back

Python program to overload multiply-Operator Overloading

8/9/2022
All Articles

#python #program #Python program function Overloading

Python program to overload multiply-Operator Overloading

Python program to overload multiply-Operator using function Overloading 

Programming languages have a feature called function overloading that enables the definition of numerous functions with the same name in a class or namespace but with different argument lists.Operator in programming enables you to create unique behaviours for function.To use of  multiplication operator *  you can define a special method  product in your class in many programming languages.

Python does not support traditional function overloading based on the number or types of arguments like some statically typed languages (e.g., C++ or Java).
There for below code is not work :-

# product is function and we are trying to overload the product method:-

def product(a, b):

    p = a * b

    print(p)

     

# Second product method

def product(a, b, c):

    p = a * b*c

    print(p)

# This line will call the second method product

product(4, 5, 5)

# This line will call the first method product

product(4,  5)

 

Below is error after execution :

ERROR!

TypeError: product() missing 1 required positional argument: 'c'
 

Example 

 
We can  implement function overloading with below  method :-
 
def product(a, b=0, c=0):
    return a + b + c
 
result1 = product(2)
result2 = product(2, 3)
result3 = product(2, 3, 4)

Conclusion 

Python does not support traditional or classic function overloading based on the number or types of arguments like some statically typed languages (e.g., C++ or Java).

You can define a single function with default arguments that handle different cases based on the number of arguments passed or you can done using  none  value of parameter.

This can be done by declaring one or more parameters in the function declaration as None. 

In order to prevent an error from happening when calling a function that has a parameter set to None but no argument provided, we will also include a checking condition for None in the function body.
 

Article