function overloading

Alex Martelli aleaxit at yahoo.com
Sat May 24 11:46:46 EDT 2003


Mirko Koenig wrote:

> Hi
> 
> I serached around the web and some tutorials but i can't finds any
> documentation about function overloading in python.

That may be because there is no such thing.


> I want to have 3 functions:
> def setPos( x, y ):
> 
> def setPos( pos ):
> 
> def setPos( object ):

You cannot have three different objects (for example, three different
functions) corresponding to the same name in the same scope.  One name,
one scope, one object.

> Is it not possible in python to overload fucntion with the same name?

Exactly!  Whenever you bind a name X to an object Y -- whether that
happens with a def statement, an assignment, or in other ways yet -- any
previous binding to the same name X in the same scope is simply forgotten.

> How do you do it?

We don't (bind several different objects to the same name in a given
scope).  If you're keen on being able to call setPos(x,y) as well as
setPos(pos) there are several ways you can achieve this effect -- e.g.

def setPos(x,y):
  "whatever"

setPos_2args = setPos

def setPos(pos):
   "whatever"

setPos_postype = setPos

def setPos(another):
   "whatever"

setPos_anyother = setPos

def setPos(*args):
    if len(args)==2: return setPos_2args(*args)
    if len(args)>1: raise TypeError
    if type(args[0]) == postype: return setPos_postype(*args)
    return setPos_anyother(*args)


Of course, it's quite unnatural and stilted to program in this way,
as is typical of such efforts to use the programming style appropriate
to language X while actually programming in very different language Y.
If you learn to program in Y's own style, you will be more productive
and generally happier.


Alex





More information about the Python-list mailing list