How do I use method overloading in Python?

user1335578 picture user1335578 · Apr 18, 2012 · Viewed 200k times · Source

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?

Answer

agf picture agf · Apr 18, 2012

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.

Edit: See PEP 443 for information about the new single dispatch generic functions in Python 3.4.