__init__ concerns

Alex Martelli aleax at aleax.it
Tue Dec 11 05:59:47 EST 2001


"Peter Wang" <pzw1 at hotmail.com> wrote in message
news:ab0cb7fb.0112102036.74cc8bfb at posting.google.com...
> i'm subclassing UserDict to journal transactions to gdbm, and i'm
> writing my own __init__() to take an open journal handle.
>
> it occurs to me that since i don't have *any idea* what the base
> class's constructor needs or does, i should probably call it, in order
> to ensure that my object is valid.  then it occurs to me that i don't
> know what the UserDict constructor looks like in its entirety, but it
> must be callable with no arguments, since i can do "x =
> UserDict.UserDict()".  so the problem is kind of solved: i can just
> call UserDict.__init__(self).
>
> however, the bigger question of properly calling parent classes'
> constructors still remains.  i figured you can always put a line into
> the subclass's constructor:
>
> def __init__(self, *args):
>     apply(BASECLASS.__init__, (self,) + args)
>
> but i thought this was kind of a kludge.  what is the proper python
> idiom (or, failing that, the proper technique) for ensuring that a
> subclass instance is properly initialized, especially when details of
> the base class are unknown?

I've posted on this thread, replying to Erik Max Francis and changing
the subject to "a class's coupling to its bases (was Re: __init__
concerns)", as to the WHY, but I hope the reply can also be useful
regarding the HOW.  apply() is indeed pretty old, but I guess you'll
have to stick with it if you're stuck on Python 1.5.2.  In modern
Python,

    def __init__(self, *args, **kwds):
        BASECLASS.__init__(self, *args, **kwds)
        # whatever else you need here

is a very typical idiom, and I don't see any "kind of a kludge" are
about it (and, of course, variations were args and/or kwds are tweaked
somehow before delegating to a base class's __init__).


Alex






More information about the Python-list mailing list