Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method overloading in python

I need to call unparameterised method first, but also parameterized first, but it is giving an error.

>>> class A:
...     def first(self):
...             print 'first method'
...     def first(self,f):
...             print 'first met',f
...
>>> a=A()
>>> a.first()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: first() takes exactly 2 arguments (1 given) 

Is it possible to do method overloading in Python like in Java?

like image 921
user1272269 Avatar asked Mar 15 '12 18:03

user1272269


2 Answers

Python doesn't do function overloading. This is a consequence of it being a loosely-typed language. Instead you can specify an unknown number of arguments and deal with their interpretation in the function logic.

There are a couple ways you can do this. You can specify specific optional arguments:

def func1(arg1, arg2=None):
    if arg2 != None:
        print "%s %s" % (arg1, arg2)
    else:
        print "%s" % (arg1)

Calling it we get:

>>> func1(1, 2)
1 2

Or you can specify an unknown number of unnamed arguments (i.e. arguments passed in an array):

def func2(arg1, *args):
    if args:
        for item in args:
            print item
    else:
        print arg1

Calling it we get:

>>> func2(1, 2, 3, 4, 5)
2
3
4
5

Or you can specify an unknown number of named arguments (i.e. arguments passed in a dictionary):

def func3(arg1, **args):
    if args:
        for k, v in args.items():
            print "%s %s" % (k, v)
    else:
        print arg1

Calling it we get:

>>> func3(1, arg2=2, arg3=3)
arg2 2
arg3 3

You can use these constructions to produce the behaviour you were looking for in overloading.

like image 168
cjm Avatar answered Oct 15 '22 00:10

cjm


Your second first method is overriding the original first method. In Python, it is not possible to create overloaded methods the same way as in Java.

However, you can create methods with optional and/or keyword-based arguments and process those accordingly. Here's an example:

class A:
    def first(self, f=None):
        if f is not None:
            print 'first met', f
        else:
            print 'first method'

Usage:

a = A()
a.first()
a.first('something')
like image 25
Platinum Azure Avatar answered Oct 15 '22 02:10

Platinum Azure