__init__ like in java

Alex Martelli aleaxit at yahoo.com
Fri Dec 22 12:03:27 EST 2000


"Gilles Lenfant" <glenfant at equod.com.nospam> wrote in message
news:91vosi$19h$1 at reader1.imaginet.fr...
> Hi,
>
> Is there an *elegant pythonic*  way to have several constructors for one
> class ?

Quoting a post of mine from earlier this month:

"""
class A:
    def __init__(self, *args):
        m=getattr(self,"_init_%d"%len(args),None)
        if m is None:
            raise TypeError, "wrong # of args (%d)"%len(args)
        m(*args)
    def _init_1(self, arg):
        print "One Arg"
    def _init_2(self, arg1, arg2):
        print "Two Args"

I think the if/elif is simpler and clearer, but, hey, whatever
floats your boat; this one can surely be more concise if you
have widely-varying possible numbers of arguments.

Note that you can (and probably should, if you do this often)
get this special dispatching-init from a mixin class:

class InitDispatchMixin:
    def __init__(self, *args):
        m=getattr(self,"_init_%d"%len(args),None)
        if m is None:
            raise TypeError, "wrong # of args (%d)"%len(args)
        m(*args)

so the various classes need just inherit from this and define
the several _init_N methods they desire.
"""

This 'overloads' the constructors based on how many arguments
are given -- how elegant (and how Pythonic...!) this is, being
of course *debatable*.  Overloading on *types* would be less
elegant *and* less Pythonic, though you could easily extend
this idea to do it -- I would discourage it even more strongly.


Alex






More information about the Python-list mailing list