super, apply, or __init__ when subclassing?

exhuma.twn exhuma at gmail.com
Tue Sep 18 08:58:17 EDT 2007


On Sep 18, 2:45 pm, Bruno Desthuilliers <bruno.
42.desthuilli... at wtf.websiteburo.oops.com> wrote:
> exhuma.twn a écrit :
>
> > This is something that keeps confusing me. If you read examples of
> > code on the web, you keep on seeing these three calls (super, apply
> > and __init__) to reference the super-class. This looks to me as it is
> > somehow personal preference. But this would conflict with the "There
> > one way to do it" mind-set.
>
> apply is deprecated. Chances are that code using it is somewhat old.
> super came with the new object model in Python 2.2.1 (IIRC), and is only
> useful for some corner cases involving multiple inheritence . Directly
> calling the superclass's method (__init__ or whatever) is the canonical
> way in the most common cases.
>
> And BTW, the sentence is "there *should* be one - and *preferably* only
> one - *obvious* way to do it" (emphasis is mine). In this case, there's
> _at least_ one way do to do it, and only one (direct call) is really
> obvious IMHO !-)
>
> > So, knowing that in python there is one thing to do something, these
> > three different calls must *do* domething different.
>
> Indeed. But mostly because you managed to get 2 examples wrong !-)
>
> > But what exactly
> > *is* the difference?
>
> > ------------ Exampel 1: -----------------------------
>
> > class B(A):
> >    def __init__(self, *args):
> >       A.__init__(self, args)
>
> You want:
>
> class B(A):
>     def __init__(self, *args):
>        A.__init__(self, *args)

Ah.. this was a typo in my original post. Oops ;)

>
> > ------------ Exampel 2: -----------------------------
>
> > class B(A):
> >    def __init__(self, *args):
> >       apply( A.__init__, (self,) + args)
>
> is the same as the previous, using the deprecated apply function.
>
> > ------------ Exampel 3: -----------------------------
>
> > class B(A):
> >    def __init__(self, *args):
> >       super(A,self).__init__(*args)
>
> You want:
>
> class B(A):
>     def __init__(self, *args):
>        super(B,self).__init__(*args)

Hmmm... and suddenly it all makes sense! Great!

Thanks all for clarifying this to a Java-Convert ;)




More information about the Python-list mailing list