How does Python's super() work with multiple inheritance? -


I'm too new to Python object-oriented programming and I have trouble understanding super > Function (New Style Classes) Especially when it comes to many heritage.

For example if you have something like this:

  class first (object): def __init __ (self): "first" square II (object): def __init __ (self): print "second class" third (first, second): def __init __ (self): super (third, self) .__ init (__) print "this is"  

What do I not get: what will be the success of both constructor methods? If so, who will be run with super and why?

What else would you like to run another? I know that there is something to do with the Python method resolution command () in it

It is by Guido himself Expanded with proper explanation (including two earlier attempts).

But, in a nutshell: in your example, the third () will call first .__ init___ . For such simple situations, for the left-to-right attribute (in this case, __ init __ ) on the parent of the Python class, so if you define

  Class III (first, second): ...  

Python will first see, and if not the first, the feature is on the other side.

This situation becomes more complex, when the heritage begins to cross the path (say, if one is already inherited from another, for example). For more information read the above link, but, in a nutshell, Python will try to maintain that order in which each class will appear in the heritage list, first child classes. For example, if you had: first class (first): def __init __ (self): print "first" square II (first): def __init __ (self): print "seconds" Class III (first): DEF __int __ (self): print "third" class IV (second, third): def __init __ (self): super (fourth, own) .__ init __ () print "this is" / Code>

MRO will be [fourth, second, third, first]. By the way: If Python can not find a solid method resolution command,

edit to add an example of a vague MRO:

  class first (object): 

def __init __ (self): print "first" square II (first): def __init __ (self): "third"

Should be the third MRO be first or [ second, first] ? There is no clear expectation, and Python will increase an error:

Type error: When calling metaclaces the base can not create a static method resolution order (MRO) for error base Second, first < / P>

[edit] I argue to many people that examples of deficiency call super () , then explain to me: issue of examples Showing how MRO has been built. They can not want to print "first \ nsecond \ third" or whatever you can - and, with example, super () call, See what happens, and can gain a deeper understanding of the succession models of Python. But my goal is to keep it simple and it shows how MRO is ready. And it has been explained:

  gt; & Gt; Fourth .__ mro__ ( 

Comments