super, apply, or __init__ when subclassing?

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Tue Sep 18 08:45:26 EDT 2007


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)


> ------------ 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)




More information about the Python-list mailing list