How do I use method overloading in Python?
class, overloading, python
Solution
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)
Problem
I am trying to implement method overloading in Python: ``` class A: def stackoverflow(self): print ('first method') def stackoverflow(self, i): print ('second method', i) ob=A() ob.stackoverflow(2) ``` but the output is `second method 2`; similarly: ``` class A: def stackoverflow(self): print ('first method') def stackoverflow(self, i): print ('second method', i) ob=A() ob.stackoverflow() ``` gives ``` Traceback (most recent call last): File "my.py", line 9, in <module> ob.stackoverflow() TypeError: stackoverflow() takes exactly 2 arguments (1 given) ``` How do I make this work?