overloading a function

Quinn Dunkan quinn at barf.ugcs.caltech.edu
Thu Mar 7 13:55:36 EST 2002


On Fri, 8 Mar 2002 00:36:46 +1100, Dave Harrison <dlharris at mail.usyd.edu.au>
wrote:
>Hi there all,
>
>If I have a function, but I want to be able to call it two different ways -
the ways being differentiated by the paramaters I pass the function) how do I
do this ??
>
>At the moment I have 
>
>def Foo(num)
>
>def Foo(num,dflt)
>
>however I am only getting the first of the two, and the second function is
ignored.

I think you mean you're only getting the second.  The first is not ignored, but
replaced, in the same way that 5 is when you type:

x = 5
x = 10

>I couldn't find anything in the documentation, any ideas ?

In the case above:

def foo(num, dflt=None):
    if dflt is None:
        ...
    ...

In general:

class A:
    def foo(self, bar):
        ...
class B:
    def foo(self, bar):
        ...

import random
x = random.choice((A(), B())
x.foo(42)


The 'foo' called depends on the type of 'x'.  You can't do this for anything
other than the first argument though, since python is mono-dispatch.  If
you really wanted you could hack together a multi-dispatch situation:

class Generic:
    def __init__(self):
        self.tab = {}
    def __call__(self, *args):
        # call before-methods?
        v = self.lookup(args)(*args)
        # and after-methods
        return v
    def lookup(self, args):
        ts = map(type, args)
        ... lookup ts in self.tab using whatever ordering rules you want
    def add_method(self, f, types)
        self.tab[types] = f

def f_ints(x, y):
    return x + y
def f_int_string(x, y):
    return '%d %s%s' %(x, y, x != 1 and 's' or '')
f = Generic()
f.add_method(f_ints, (int, int))
f.add_method(f_int_str, (int, str))


It's not very pythonic though.



More information about the Python-list mailing list