Python | Method Overloading
Two or more methods have the same name but different numbers of parameters or different types of parameters, or both. These methods are called overloaded methods and this is called method overloading.
Like other languages (for example, method overloading in C++) do, python does not support method overloading by default. But there are different ways to achieve method overloading in Python.
The problem with method overloading in Python is that we may overload the methods but can only use the latest defined method.
In the above code, we have defined two product methods we can only use the second product method, as python does not support method overloading. We may define many methods of the same name and different arguments, but we can only use the latest defined method. Calling the other method will produce an error. Like here calling product(4,5) will produce an error as the latest defined product method takes three arguments.
Thus, to overcome the above problem we can use different ways to achieve the method overloading.
Method 1 (Not The Most Efficient Method):
We can use the arguments to make the same function work differently i.e. as per the arguments.
11 Hi Geeks
Method 2 (Not the efficient one):
We can achieve method overloading in python by user defined function using “None” keyword as default parameter.
The first parameter of “add” method is set to None. This will give us the option to call it with or without a parameter.
When we pass arguments to the add method (Working):
- The method checks if both the parameters are available or not.
- As we have already given default parameter values as “None”, if any of the value is not passed it will remain “None”.
- Using If-Else statements, we can achieve method overloading by checking each parameter as single statement.
The problem with above methods is that, it makes code more complex with multiple if/else statement and is not the desired way to achieve the method overloading.
Method 3 (Efficient One):
By Using Multiple Dispatch Decorator
Multiple Dispatch Decorator Can be installed by:
pip3 install multipledispatch
If pip is not installed on your device:
6 12 17.985999999999997
In Backend, Dispatcher creates an object which stores different implementation and on runtime, it selects the appropriate method as the type and number of parameters passed.
Please Login to comment...