views:

14909

answers:

2

Trying to understand super(). From the looks of it, both child classes can be created just fine. Im curious as to what difference there actually is in this code:

class Base(object):
    def __init__(self):
        print "Base created"

class ChildA(Base):
    def __init__(self):
        Base.__init__(self)

class ChildB(Base):
    def __init__(self):
        super(ChildB, self).__init__()

print ChildA(),ChildB()
+3  A: 

There isn't, really. super() looks at the next class in the MRO (method resolution order, accessed with cls.__mro__) to call the methods. Just calling the base __init__ calls the base __init__. As it happens, the MRO has exactly one item-- the base. So you're really doing the exact same thing, but in a nicer way with super() (particularly if you get into multiple inheritance later).

Devin Jeanpierre
I see. Could you elaborate a little as to why its nicer to use super() with multiple inheritance? To me, the base.__init__(self) is shorter (cleaner). If I had two baseclasses, it would be two of those lines, or two super() lines. Or did I misunderstand what you meant by "nicer"?
mizipzor
Actually, it would be one super() line. When you have multiple inheritance, the MRO is still flat. So the first super().__init__ call calls the next class's __init__, which then calls the next, and so on. You should really check out some docs on it.
Devin Jeanpierre
The child class MRO contains object too - a class's MRO is visible in the __mro__ class variable.
Alabaster Codify
Also note that classic classes (pre 2.2) don't support super - you have to explicitly refer to base classes.
Alabaster Codify
"The child class MRO contains object too - a class's MRO is visible in the __mro__ class variable." That is a big oops. Whoops.
Devin Jeanpierre
+23  A: 

Super lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven't already.

Edit: Note that the syntax changed in Python 3.0: you can just say super().__init__() instead of super(ChildB, self).__init__() which IMO is quite a bit nicer.

Kiv
I agree. It means that not only do you not have to mention the parent class's name, but you don't have to mention the current class's name.
Devin Jeanpierre