How do I use method overloading in Python?

It’s method overloading, not method overriding. And in Python, you historically do it all in one function:

class A:
    def stackoverflow(self, i='some_default_value'):
        print 'only method'

ob=A()
ob.stackoverflow(2)
ob.stackoverflow()

See the Default Argument Values section of the Python tutorial. See “Least Astonishment” and the Mutable Default Argument for a common mistake to avoid.

See PEP 443 for information about the single dispatch generic functions added in Python 3.4:

>>> from functools import singledispatch
>>> @singledispatch
... def fun(arg, verbose=False):
...     if verbose:
...         print("Let me just say,", end=" ")
...     print(arg)
>>> @fun.register(int)
... def _(arg, verbose=False):
...     if verbose:
...         print("Strength in numbers, eh?", end=" ")
...     print(arg)
...
>>> @fun.register(list)
... def _(arg, verbose=False):
...     if verbose:
...         print("Enumerate this:")
...     for i, elem in enumerate(arg):
...         print(i, elem)

Leave a Comment