function overloading

Martin v. Löwis martin at v.loewis.de
Sat May 24 11:55:33 EDT 2003


Mirko Koenig <koenig at v-i-t.de> writes:

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

Because there just is no function overloading in Python.

> I want to have 3 functions:

However, you cannot get them:

> def setPos( x, y ):
> 
> def setPos( pos ):
> 
> def setPos( object ):

A def statement is roughly executed like this:
1. Compile the body of the function.
2. Build a function object __f
3. Assign it:
   setPos = _f

So the second definition just overwrites the earlier one.

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

No, it's not possible. I strongly recommend that you find different
function names. If you absolutely must have all three functions with
the same name, you can write the function like this

def setPos(*args):
  assert 0 < len(args) < 3
  if len(args) == 2:
     x,y = args
     ...
  elif args[0] is a position:
     pos = args[0]
     ...
  else:
     object = args[0]
     ...

HTH,
Martin





More information about the Python-list mailing list