When a function is defining multiple times to perform multiple tasks is known as function overloading.
Here function name is same but they are different by their signatures.
Python does not support function overloading like other languages(for example, method overloading in C++, Java). But there are different ways that we can achieve method overloading in Python.
Here in python function overloading the problem is that we can overload the methods but can only use the latest defined method.
It is an example of polymorphism.
def area(length,breadth): a=length * breadth print("the area of rectangle is",a) def area(r): arr=3.141 * r * r print("area of circle is ",arr) #area(5,6) #function call area(3.4) #function call
In the above program, we have defined two area( ) function, but we can only use the second area( ) function, as python does not support function overloading. We may define many functions of the same name and different arguments, but we can only use the latest defined function.
Here if we will call add(5,6), then it will give error as the latest defined area( ) function taking one argument. Hence to eliminate this drawback, we can use another approach to achieve the function overloading.
#Python function overloading from multipledispatch import dispatch @dispatch(int,int) def area(length,breadth): a=length * breadth print("the area of rectangle is",a) @dispatch(float) def area(r): arr=3.141 * r * r print("area of circle is ",arr) area(5,6) #function call area(3.4) #function call
Here in the above program, the control is clearly understanding two area() functions are different based on their signature due to using dispatcher. Dispatcher(that is @dispatch) representing type specification explicitly. So in first function call that is area(5,6) representing area of rectangle and second area(3.4) function call representing area of circle.
So area() function having ability to take more than one form one is area of rectangle and one is area of circle, hence function overloading is an example of polymorphism.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc