Q: Can methods and functions be overloaded?

Carel Fellinger cfelling at iae.nl
Thu Feb 15 19:59:30 EST 2001


Claudius Schnörr <schnoerr at mailzone.com> wrote:
> Hello,

> I would appreciate to write methods for different counts of
> arguments, say
> f(self, a) and f( self, b, c, d ) or so where b and a have to be handled
> differently.

> Is this possible? I think no because the second definition of f
> overwrites the first one.

Head on:)
but head up, Python is very flexible, so build your own overloader

class Overloaded:
    __overload = {}

    def f(self, *args):
        apply(self.__overload[len(args)], (self,) + args)

    def f1(self, a):
        print a
    __overload[1] = f1

    def f2(self, a, b):
        print a, 'and', b
    __overload[2] = f2


u = Overloaded()
u.f('spam')
u.f('spam', 'spam')

-- 
groetjes, carel



More information about the Python-list mailing list