Method overloading, as known in many object-oriented programming languages, refers to defining more than one methods with the same name but different sets of arguments.
Unlike Java or C++, Python does not support method overloading in its traditional form. However, we can achieve similar functionality with the help of other ways possible.
Why Doesn’t Python Support Method Overloading?
Traditional method overloading is not possible in Python due to the support for dynamic typing and variable-length arguments. If a class consisting of multiple methods sharing same name, the most recently defined method will overwrite the rest of the methods.
This is because the functions in Python are treated as objects and are stored in a class’s internal dictionary, where the name of the method serves as the key and the function object as the value. As a result, redefining a method simply replaces the previous one.
Therefore, redefining a method results in replacing the stored function object with the updated one.
Example: Traditional Method Overloading (Not Supported)
Let us take an exampe to demonstrate the method overloading in Python.
Example
# traditional method overloading
# creating a class
class Example:
# show() method with single argument
def show(self, a):
print(f"Single argument: {a}")
# show() method with two arguments
def show(self, a, b):
print(f"Two arguments: {a}, {b}")
# instantiating the class
obj = Example()
# calling the method
obj.show(5)
Output:
TypeError: Example.show() missing 1 required positional argument: 'b'
In this example, we have created a class ‘Example’ consisting of two show() methods. The first method is replaced by the second one implying that the first one is not accessible anymore.
How to perform Method Overloading in Python?
Since, the method overloading in Python cannot be done traditionally, there are few other ways to achieve method overloading, including:
- Using Default Parameter Values
- Using *args
- Using @singledispatch from functools
- Using @dispatch from multipledispatch
Let us understand each of these methods with the help of examples.
Method 1: Using Default Parameter Values
In Python, we are allowed to assign default values to the methods’ parameters. This lets a single method behave differently depending on how many arguments are passed. This way we can effectively simulate overloading in Python.
Let us see an example showing the use of default parameter values.
Example
# creating a class
class Simple_Calculator:
# defining a function to add numbers
def add(self, a, b = 0, c = 0):
'''''
This method has few default parameter values set to 0
'''
return a + b + c
# creating an object
my_calculator = Simple_Calculator()
# calling the add() method
print(my_calculator.add(5)) # single argument
print(my_calculator.add(5, 10)) # two arguments
print(my_calculator.add(5, 10, 15)) # three arguments
Output:
5
15
30
Explanation:
The add() method is adaptable as it uses default values for parameters b and c. When the method is called with only one argument, thus b and c default to 0. When two arguments are provided, only c defaults to 0.
While this approach is functional and flexible, it fails to achieve true overloading as Python treats it as a single method with optional parameters, unlike some other languages that support multiple methods with the same name.
Method 2: Using *args (Variable-length Arguments)
Python provides tools like *args that allow a single method to accept a variable number of positional arguments. This way we can simulate method overloading by writing logic that behaves differently on the basis of the number or type of arguments passed.
We will now see an example.
Example
# creating a class
class Simple_Calculator:
# defining a function to add numbers
def add(self, *args):
'''''
This method uses positional arguments
'''
return sum(args)
# creating an object
my_calculator = Simple_Calculator()
# calling the add() method
print(my_calculator.add(6)) # single argument
print(my_calculator.add(6, 12)) # two arguments
print(my_calculator.add(6, 12, 18)) # three arguments
Output:
6
18
36
Explanation:
In this example, the add() method is highly flexible as we are using *args. This allows us to pass any number of arguments to the method, making it easier to calculate sum of multiple values without defining multiple method versions.
While this improves the flexibility of the add() method, it can lead to unintentional errors due to lack of control over the types of provided parameters – a relative lack of type control could result in surprising problems further down the line.
Since there is no strict distinction between the types of arguments, the method becomes harder to manage and debug – sacrificing clarity and potentially performance in the process.
Method 3: Using @singledispatchmethod from functools
In Python, @singledispatchmethod is a decorator from the functools module that helps us overload methods on the basis of the type of the first argument, especially within the class methods.
Let us look at the following to understand the working of the @singledispatchmethod decorator.
Example
# importing the required attribute from module
from functools import singledispatchmethod
# creating a class
class Simple_Calculator:
# defining a method to calculate sum of two numbers
@singledispatchmethod
def add(self, a, b):
# raising error for unsupported data type
raise NotImplementedError("Unsupported Data Type")
# method overloading for variables of int data type
@add.register(int)
def _(self, a: int, b: int) -> int:
return a + b
# method overloading for variables of float data type
@add.register(float)
def _(self, a: float, b: float) -> float:
return a + b
# creating an object
my_calculator = Simple_Calculator()
# calling the add() method
print(my_calculator.add(9, 14)) # only int variables
print(my_calculator.add(3.72, 1.54)) # only float variables
try:
print(my_calculator.add("tpoint", "tech")) # trying to pass str
except NotImplementedError as e:
print(e)
Output:
23
5.26
Unsupported Data Type
Explanation:
In this example, we have used the @singledispatchmethod decorator to overload the add() method on the basis of the type of the arguments. We have handled int and float inputs, and raised an error for any unsupported data types (e.g., str).
Method 4 (Optional): Using @dispatch from multipledispatch
Apart from the three discussed earlier, there is one another method that we can use to achieve method overloading. This requires us to install a third-party library known as multipledispatch.
This library enables true multiple dispatch, meaning we can select a function or method implementation on the basis of the data types of all parameters, not just the first one.
To install the multipledispatch method, we can use pip installer as shown below:
Syntax:
$ pip install multipledispatch
Now let us see an example to understand the use of @dispatch property offered by this module.
Example
# importing the required attribute from module
from multipledispatch import dispatch
# creating a class
class Simple_Calculator:
# defining a method to calculate sum of two numbers
# method overloading for only int data type
@dispatch(int, int)
def add(self, a, b):
return a + b
# method overloading for only float data type
@dispatch(float, float)
def add(self, a, b):
return a + b
# method overloading for first int then float
@dispatch(int, float)
def add(self, a, b):
return a + b
# method overloading for first float then int
@dispatch(float, int)
def add(self, a, b):
return a + b
# creating an object
my_calculator = Simple_Calculator()
# calling the add() method
print(my_calculator.add(9, 14)) # int + int
print(my_calculator.add(3.72, 1.54)) # float + float
print(my_calculator.add(12, 5.2)) # int + float
print(my_calculator.add(1.7, 0.56)) # float + int
Output:
23
5.26
17.2
2.26
Explanation:
In this example, the dispatch creates an object which stores different implementation. During runtime, it selects the appropriate method as the type and number of arguments passed.
Note: @dispatch from multipledispatch is not a built-in Python feature. It comes from an external library and may not be ideal for performance-critical applications.
Conclusion
In this example, we learn what method overloading is and the reason why Python does not support traditional method overloading. In order to achieve method overloading with Python, we discussed several approaches including – the use of default values for parameters or positional arguments, and decorators like @singledispatch from functools and @dispatch from the multipledispatch module. We also learned how these approaches help delivering the similar effect.









