Demystify super in python?

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

class A(object): def __init__(self): print "in A init" class B(object): def __init__(self): print "in B init" class C(A,B): def __init__(self): super(C,self).__init__() print "In C" if __name__=="__main__": c=C() 

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

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

I don't understand why super(A,c).__init__() prints it to B init ??

+3
source share
1 answer

Python super () should have been called "next-in-mro" because it does not necessarily call up the parent; rather, he can name a sibling.

It is easy to check the resolution order of the method 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 allows the super-call chain to visit each class in the chain no more than once. This maintains a programming style called "collaborative multiple inheritance," which is sometimes very useful.

Here are some links, including links to the following Dylan method, which served as the model for Python super ():

+9
source

Source: https://habr.com/ru/post/1274477/


All Articles