Can methods and functions be overloaded?

Steve Holden sholden at holdenweb.com
Fri Feb 16 02:38:59 CET 2001


"Claudius Schnörr" <schnoerr at mailzone.com> wrote in message
news:3A8C4CEA.B418B56E at mailzone.com...
> 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.
>
> Any hints are welcome.
> Please email a copy of your answer directly to
>     Claudius.Schnoerr at ddg.de
>
> Thank you in advance,
>
> Claudius
>
Well, you can use a notation which passes all positional arguments in a
list.

Without testing, something like:

    def meth1(self, *args):
        if len(args) == 1:
            # code one-argument case
        else:
            # code more-than-one-argument case

Another option might be to provide keyword default arguments for the
additional arguments, as in:

    def meth2(self, a, b=None, c=None):
        if b == c == None:
            # code one-argument case
        else:
            # code more-than-one-argument case

Does this help, or did you alredy know about it? I'm afraid Python doesn't
allow the same kind of method overloading by signature that, say, Java and
C++ do.

regards
 Steve





More information about the Python-list mailing list