Calling the parent class' __init__

Jeremy Hylton jhylton at my-deja.com
Fri Oct 6 11:08:19 EDT 2000


In article <yayvgv6ci0l.fsf at ganglot.ifi.uio.no>,
  Vetle Roeim <vr at acm.org> wrote:
> or:
>   class C(A):
>       def __init__(self, val1, **keywordvals):
>           apply(A.__init__, (self, val1), keywordvals)
>
> the-possibilities-are-endless-ly y'rs, vr
>

Here are a couple of more possibilities:

class C(A):
    def __init__(self, val, **kw):
        A.__init__(self, val, **kw)

and my personal preference

class C(A):
    __super_init = A.__init__
    # also assign any of A's methods that are overridden
    def __init__(self, val, **kw):
        self.__super_init(val, **kw)

I prefer this version for two reasons.  First, the calls to methods in
the base class don't have to pass self explicitly; they look like
regular methods calls.  Second, if you collect all the overridden method
assignments at the top of the class, it makes the class easier to read
and maintain.  All the information about what superclass methods are
overridden are collected in one place.  If you change your class
hierarchy, you don't have to search through the entire body of the class
to find references to the old superclass and update them.

--
-- Jeremy Hylton, <http://www.python.org/~jeremy/>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list