Sometimes, we want to use method overloading in Python.
In this article, we’ll look at how to use method overloading in Python.
How to use method overloading in Python?
To use method overloading in Python, we can use the pythonlangutil
module.
To install it, we run
pip install pythonlangutil==0.1
Then we can use it by writing
from pythonlangutil.overload import Overload, signature
class A:
@Overload
@signature()
def foo(self):
print('first method')
@foo.overload
@signature("int")
def foo(self, i):
print('second method', i)
to define the class A
with 2 foo
methods.
This is possible since we have the decorators provided by pythonlangutil
called to modify the methods.
The original foo
method has the Overload
and signature
decorators called on it.
And then 2nd foo
method had the foo.overload
decorator and the signature
decorators called it.
We call signature
with 'int'
to make sure i
is an int.
Conclusion
To use method overloading in Python, we can use the pythonlangutil
module.