views:

292

answers:

3
class A:
 def __init__(self):
   print "world"

class B(A):
 def __init__(self):
   print "hello"

B()
hello

In all other languages I've worked with the super constructor is invoked implicitly. How does one invoke it in Python? I would expect super(self) but this doesn't work

+7  A: 

super() returns a parent-like object in new-style classes:

class A(object):
 def __init__(self):
   print "world"

class B(A):
 def __init__(self):
   print "hello"
   super(B, self).__init__()

B()
Ignacio Vazquez-Abrams
just of curiosity why does `super(B,self)` require both B and self to be mentioned? isn't this redundant? shouldn't self contain a reference to B already?
Mike
No, because `self` might actually be an instance of `C`, a child of `B`.
Ignacio Vazquez-Abrams
+1  A: 

With old-style classes it would be this:

class A: 
 def __init__(self): 
   print "world" 

class B(A): 
 def __init__(self): 
   print "hello" 
   A.__init__(self)
Gabe
A: 

One way is to call A's constructor and pass self as an argument, like so:

class B(A):
    def __init__(self):
        A.__init__(self)
        print "hello"

The advantage of this style is that it's very clear. It call A's constructor. The downside is that it doesn't handle diamond-shaped inheritance very well, since you may end up calling the shared base class's constructor twice.

Another way is to user super(), as others have shown. For single-inheritance, it does basically the same thing as letting you call the parent's constructor.

However, super() is quite a bit more complicated under-the-hood and can sometimes be counter-intuitive in multiple inheritance situations. On the plus side, super() can be used to handle diamond-shaped inheritance. If you want to know the nitty-gritty of what super() does, the best explanation I've found for how super() works is here (though I'm not necessarily endorsing that article's opinions).

Daniel Stutzbach