Method Overloading in Python
Last updated on 25th Sep 2020, Artciles, Blog
In Python you can define a method in such a way that there are multiple ways to call it. Given a single method or function, we can specify the number of parameters ourself. Depending on the function definition, it can be called with zero, one, two or more parameters. This is known as method overloading.
What is Method Overloading?
In oops we have different types of elements like Object, Class and etc. in these elements we implement the reusability in two elements are Inheritance and Polymorphism. In this topic, Method overloading is in Polymorphism. Polymorphism is a technique of producing different functionality with a single format.
Subscribe For Free Demo
Error: Contact form not found.
Here we have two types of polymorphism.
- Method Overloading
- Method Overriding
Method Overloading:
- Method Overloading is the class having methods that are the same name with different arguments.
- Arguments differently will be based on a number of arguments and types of arguments.
- It is used in a single class.
- It is also used to write the code clarity as well as reduce complexity.
Method Overriding:
- Method Overriding is the method having the same name with the same arguments.
- It is implemented with inheritance also.
- It is mostly used for memory reducing processes.
Method Overloading in Python
Method overloading is one concept of Polymorphism. It comes under the elements of OOPS. It is actually a compile-time polymorphism. It is worked in the same method names and different arguments. Here in Python it also supports oops concepts. But it is not oops based language. It also supports this method overloading also.
Normally in python, we don’t have the same names for different methods. But overloading is a method or operator to do the different functionalities with the same name. i.e methods differ their parameters to pass to the methods whereas operators have differed their operand.
Here some advantages of Method Overloading in Python.
- Normally methods are used to reduce complexity. Method overloading is even it reduce more complexity in the program and also improves the clarity of code.
- It is also used for reusability.
It has some disadvantages also when creating more confusion during the inheritance concepts.
In python, we create a single method with different arguments to process the Method Overloading. Here we create a method with zero or more parameters and also define the methods based on the number of parameters.
Example:
class Employee:
- def Hello_Emp(self,e_name=None):
- if e_name is not None:
- print(“Hello “+e_name)
- else:
- print(“Hello “)
- emp1=Employee()
- emp1.Hello_Emp()
- emp1.Hello_Emp(“Besant”)
In this example class called Employee having a method called Hello_Emp(). This method is used as a method overloading concept. It will be done by using the parameters. Here we use the parameter called e_name is set as None. If I call this method using objects during that time if I pass the value to the parameter means it prints the value. Otherwise, it is not print anything. So here we have two functionalities that will be executed in this program.
Output:
Hello
Hello Besant
In this output, we first call the method Hello_Emp without any parameter so that it prints only Hello.
Next time we call the same method with parameter value as besant so it will prints Hello Besant.
Example:
class Area:
- def find_area(self,a=None,b=None):
- if a!=None and b!=None:
- print(“Area of Rectangle:”,(a*b))
- elif a!=None:
- print(“Area of square:”,(a*a))
- else:
- print(“Nothing to find”)
- obj1=Area()
- obj1.find_area()
- obj1.find_area(10)
- obj1.find_area(10,20)
Output:
Nothing to find Area of a square: 100
Area of Rectangle: 200
In this example also we implement the Method Overloading concept with help of Parameters. In this example use to find the area of different shapes. If you get the area of square means you just pass the value for the parameter itself. In the same method if you want to find a rectangle area means you pass the value for both a and b values. If you pass without any value means it will return nothing to find.
Invoking the function
As stated above, the __call__ method within class Function is invoked every time a function decorated with an overload decorator is called. We use this function to fetch the appropriate function using the get function of namespace and invoke the required implementation of the overloaded function. The __call__ method is implemented as follows
- def __call__(self, *args, **kwargs):
- “””Overriding the __call__ function which makes the
- instance callable.
- “””
- # fetching the function to be invoked from the virtual namespace
- # through the arguments.
- fn = Namespace.get_instance().get(self.fn, *args)
if not fn:
- raise Exception(“no matching function found.”)
- # invoking the wrapped function and returning the value.
- return fn(*args, **kwargs)
The method fetches the appropriate function from the virtual namespace and if it did not find any function it raises an Exception and if it does, it invokes that function and returns the value.
Function overloading in action
Once all the code is put into place we define two functions named area: one calculates the area of a rectangle and the other calculates the area of a circle. Both functions are defined below and decorated with an overload decorator.
- @overload
- def area(l, b):
- return l * b
- @overload
- def area(r):
- import math
- return math.pi * r ** 2
- >>> area(3, 4)
- 12
- >>> area(7)
- 153.93804002589985
When we invoke an area with one argument it returns the area of a circle and when we pass two arguments it invokes the function that computes the area of a rectangle thus overloading the function area. You can find the entire working demo here.
Conclusion
Python does not support function overloading but by using common language constructs we hacked a solution to it. We used decorators and a user-maintained namespace to overload functions and used the number of arguments as a disambiguation factor. We could also use data types (defined in decorator) of arguments for disambiguation – which allows functions with the same number of arguments but different types to overload. The granularity of overload is only limited by function getfullargspec and our imagination. A neater, cleaner and more efficient approach is also possible with the above constructs so feel free to implement one and tweet me @arpit_bhayani, I will be thrilled to learn what you have done with it.
Are you looking training with Right Jobs?
Contact Us- Top Python Framework’s
- Python Interview Questions and Answers
- Python Tutorial
- Advantages and Disadvantages of Python Programming Language
- Python Career Opportunities
Related Articles
Popular Courses
- Java Online Training
11025 Learners
- C And C Plus Plus Online Training
12022 Learners
- Dot Net Training
11141 Learners
- What is Dimension Reduction? | Know the techniques
- Difference between Data Lake vs Data Warehouse: A Complete Guide For Beginners with Best Practices
- What is Dimension Reduction? | Know the techniques
- What does the Yield keyword do and How to use Yield in python ? [ OverView ]
- Agile Sprint Planning | Everything You Need to Know