function overloading

Cliff Wells LogiplexSoftware at earthlink.net
Fri Jul 4 00:00:50 CEST 2003


On Wed, 2003-07-02 at 23:33, Jere Kahanpaa wrote:
> Hi.
> 
> Mirko Koenig <koenig at v-i-t.de> wrote:
> > I serached around the web and some tutorials but i can't finds any
> > documentation about function overloading in python.
> 
> > I want to have 3 functions:
> > def setPos( x, y ):
> > def setPos( pos ):
> > def setPos( object ):
> > ( pos and object are classes i wrote )
> 
> The normal Pythonic way is probably as follows:
> 
> def setPos(position):
>    """
>    Set Position. 
> 
>    The 'position' argument should be one of
>       * a tuple of coordinates (x,y)
>       * a instance of class Pos
>       * a instance of class Object
>    """
> 
>    if type(positions) is types.TupleType or type(positions) is types.ListType: 
>        x,y = positions
>        ...   
>    else if: 
>       ... identify object type and process


Or you could implement something like this, if think you "need"
overloading so badly that the horrific overhead added to each function
call is tolerable:

class overload(object):
    def __init__(self, *args):
        self._funcs = {}
        for f, p in args:
            self._funcs[tuple([type(a) for a in p])] = f

    def __call__(self, *args):
        f = self._funcs[tuple([type(a) for a in args])]
        return f(*args)



def f_noargs():
    print "noargs"

def f_int(a, b):
    print "ints", a, b

def f_str(a, b):
    print "str", a, b

def f_strint(a, b):
    print "strint", a, b

f = overload(
    [ f_noargs, () ],
    [ f_int, (int(), int()) ],
    [ f_str, (str(), str()) ],
    [ f_strint, (str(), int()) ]
    )
    

f()
f(1, 2)
f('a', 'b')
f('c', 3)

    
> It's hard to think outside the box when you ARE the box.

Or if the box is full of Chicken McNuggets.  Mmmm.

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726  (800) 735-0555






More information about the Python-list mailing list