How do I use method overloading in Python? How do I use method overloading in Python? python python

How do I use method overloading in Python?


It's method overloading, not method overriding. And in Python, you 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()

You can't have two methods with the same name in Python -- and you don't need to.

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 new single dispatch generic functions in Python 3.4.


You can also use pythonlangutil:

from pythonlangutil.overload import Overload, signatureclass A:    @Overload    @signature()    def stackoverflow(self):            print 'first method'    @stackoverflow.overload    @signature("int")    def stackoverflow(self, i):        print 'second method', i


In Python, you don't do things that way. When people do that in languages like Java, they generally want a default value (if they don't, they generally want a method with a different name). So, in Python, you can have default values.

class A(object):  # Remember the ``object`` bit when working in Python 2.x    def stackoverflow(self, i=None):        if i is None:            print 'first form'        else:            print 'second form'

As you can see, you can use this to trigger separate behaviour rather than merely having a default value.

>>> ob = A()>>> ob.stackoverflow()first form>>> ob.stackoverflow(2)second form