4

I was trying to understand how super works in python and tried the following example:

class A(object):
    def __init__(self):
        print "in A's init"

class B(object):
    def __init__(self):
        print "in B's init"

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

if __name__=="__main__":
    c=C()

fairly simple.. And I tried the following super calls(displayed with the results here):

>>> super(B,c).__init__()
>>> super(B,c).__init__()
>>> super(A,c).__init__()
    in B's init
>>> super(A,c).__init__()
    in B's init
>>> super(A,c).__init__()
    in B's init
>>> super(B,c).__init__()
>>> super(C,c).__init__()
    in A's init

I do not understand why does super(A,c).__init__() print out that its in B's init??

karthikr
  • 97,368
  • 26
  • 197
  • 188
py_newbie
  • 136
  • 13
  • This is a recurrent question. The answer could be reach at http://stackoverflow.com/questions/576169/understanding-python-super-and-init-methods – Mauro Baraldi Jul 04 '14 at 00:05
  • 3
    This is a great post about super: http://rhettinger.wordpress.com/2011/05/26/super-considered-super/ – Hernan Jul 04 '14 at 00:34
  • Hernan's link is useful. As a counterpoint, it's also useful to know about some of the problems with `super`: https://fuhm.net/super-harmful/ – user2357112 Jul 04 '14 at 00:37
  • @MauroBaraldi: Nothing in the answers to that question goes into any detail on multiple inheritance. The closest they get is linking to other information. – user2357112 Jul 04 '14 at 00:39

1 Answers1

9

Python's super() should have been been called "next-in-mro" because it doesn't necessarily call upwards to a parent; rather, it can call a sibling instead.

It is easy to inspect the method resolution order of your class structure:

 >>> C.__mro__
 (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>)

You can see that B is the next class after A.

The reason for this design is that it lets the chain of super calls visit every class in the chain no more than once. That supports a style of programming called "cooperative multiple inheritance" which is sometimes very useful.

Here are some references including links to Dylan's next-method that served as a model for Python's super():

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485