super, apply, or __init__ when subclassing?

exhuma.twn exhuma at gmail.com
Tue Sep 18 11:04:29 EDT 2007


On Sep 18, 2:50 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Tue, 18 Sep 2007 04:33:11 -0300, exhuma.twn <exh... at gmail.com> escribi?:
>
> > 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.
>
> > So, knowing that in python there is one thing to do something, these
> > three different calls must *do* domething different. But what exactly
> > *is* the difference?
>
> There are a few typos in your examples. If you write them this way:
>

Example 3 was not really a typo on my side. While I was browsing
around for python, I saw this in a code-fragment. So I thought this
was the way to do it. Even though I thought "super(A..." does not make
sense in a "semantic" way. Instead of just accepting this as a fact I
probably should have trusted my gut-feeling and investigate.

Nonetheless the posts (and explanations) here were really helpful for
me to understand what's happening under the hood. But seeing these
three variants of doing (nearly) the same was an itch I finally
decided to scratch. So far I blindly used "Example 1" as it seemed to
work for me.

>
>
> > ------------ Exampel 1: -----------------------------
>
> > class B(A):
> >    def __init__(self, *args):
> >       A.__init__(self, *args)
>
> > ------------ Exampel 2: -----------------------------
>
> > class B(A):
> >    def __init__(self, *args):
> >       apply( A.__init__, (self,) + args)
>
> > ------------ Exampel 3: -----------------------------
>
> > class B(A):
> >    def __init__(self, *args):
> >       super(B,self).__init__(*args)
>
> then 2 is exactly the same as 1 but using a deprecated function. And 3 is  
> the same as 1 only when there is single inheritance involved (and you are  
> using new-style classes). But see the thread "super() doesn't get  
> superclass"
>
> --
> Gabriel Genellina





More information about the Python-list mailing list