Python does not overload functions. This is due to the fact that it is a freely typed language. Instead, you can specify an unknown number of arguments and process their interpretation in function logic.
There are several ways to 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)
By causing this, 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
By causing this, we get:
>>> func2(1, 2, 3, 4, 5) 2 3 4 5
Or you can specify an unknown number of named arguments (i.e. the arguments passed in the dictionary):
def func3(arg1, **args): if args: for k, v in args.items(): print "%s %s" % (k, v) else: print arg1
By causing this, we get:
>>> func3(1, arg2=2, arg3=3) arg2 2 arg3 3
You can use these constructs to create the behavior you were looking for when overloaded.
cjm Mar 15 '12 at 18:52 2012-03-15 18:52
source share