Python method overloading

Python Method Overloading

Method overloading is a key feature of object-oriented programming. Java, C++, and C# all support method overloading, but Python doesn’t.

Method overloading occurs when a method with the same name is defined more than once in a class, but with different parameter types and/or return types. Python does not support this mechanism, as shown in the following code −

Example

class example:
def add(self, a, b):
x = a+b
return x
def add(self, a, b, c):
x = a+b+c
return x

obj = example()

print (obj.add(10,20,30))
print (obj.add(10,20))

Output

The first call to the add() method with three arguments succeeds. However, calling the add() method with two arguments, as defined in the class, fails.

60
Traceback (most recent call last):
File "C:Usersuserexample.py", line 12, in <module>
print (obj.add(10,20))
^^^^^^^^^^^^^^^
TypeError: example.add() missing 1 required positional argument: 'c'

The output tells you that Python only considers the most recent definition of the add() method and discards earlier definitions.

To simulate method overloading, we can use one, two, or three parameters by defining the default values of the method parameters as None.

Example

class example:
def add(self, a = None, b = None, c = None):
x = 0
if a != None and b != None and c != None:
x = a+b+c
elif a != None and b != None and c == None:
x = a+b
return x

obj = example()

print (obj.add(10,20,30))
print (obj.add(10,20))

It will produce the following output: −

60
30

With this solution, we can implement method overloading in Python classes.

Python’s standard library makes no other provisions for implementing method overloading. However, we can use the dispatch function from a third-party module called Multipledispatch for this purpose.

First, you need to install the Multipledispatch module.

pip install multipledispatch

This module uses the @dispatch decorator. It accepts the number of arguments to pass to the method being overloaded. Define multiple copies of the add() method with the @dispatch decorator as follows −

Example

from multipledispatch import dispatch
class example:
@dispatch(int, int)
def add(self, a, b):
x = a+b
return x
@dispatch(int, int, int)
def add(self, a, b, c):
x = a+b+c
return x

obj = example()

print (obj.add(10,20,30))
print (obj.add(10,20))

Output

When you execute this code, the following output is produced −

60
30

Leave a Reply

Your email address will not be published. Required fields are marked *