[Tutor] Calling super classs __init__?

Kent Johnson kent37 at tds.net
Fri Mar 21 12:48:30 CET 2008


tiger12506 wrote:
 > Also, does anyone want to clarify? I thought that super() only return 
one of
 > the base classes and was frowned upon for objects using multiple
 > inheritance???

super() returns the next class in method-resolution order. super() was 
added to the language specifically to address some problems introduced 
by multiple inheritance.

http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html#SECTION000330000000000000000

Actually super() doesn't return a class at all, it returns an object of 
type 'super' that is a proxy for the actual class. And the class it 
proxies may not even be an ancestor of the class named as the first 
argument. For example:

class A(object):
     def v(self):
         print 'A'

class B(A):
     def v(self):
         print 'B'
         super(B, self).v()

class C(A):
     def v(self):
         print 'C'
         super(C, self).v()

class D(B, C):
     def v(self):
         print 'D'
         super(D, self).v()

D().v()

prints
D
B
C
A

so super(B, D()) points to C which is not a base class of B at all; it 
*is* the next class after B in D.__mro__ which is
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, 
<class '__main__.A'>, <type 'object'>)

The super() docs are quite inaccurate on this point. There is already an 
issue for this in Roundup that seems to have foundered on how to explain 
some of the finer points of super(). (Hmmm... "If the implementation is 
hard to explain, it's a bad idea." What if it is impossible to explain 
:-) The issue has some suggested improvements for the docs:
http://bugs.python.org/issue1163367


Andreas Kostyrka wrote:
> This way, if all classes use super, they can cooperativly call all
> implementations of a given method.

The key here is "if all classes use super". super() needs to be used 
consistently in an inheritance hierarchy.

> That's the theory. In practice there are a number of pitfalls which
> makes super problematic. ;)

Yes. Here is a fairly lengthy document from the Chandler project about 
the correct way to use super:
http://chandlerproject.org/bin/view/Projects/UsingSuper

The complications lead some people to conclude either that super() is 
either too broken or too complicated to use:
http://fuhm.net/super-harmful/

Guido's response to the above:
http://mail.python.org/pipermail/python-dev/2005-January/050656.html

For myself, I have concluded that super() is difficult to use correctly 
and addresses problems that I have never had in practice, so I don't use it.

Kent


More information about the Tutor mailing list