The multi-inheritance MRO algorithm of Python

Source: Internet
Author: User

MRO is the method Resolution order, which is proposed mainly to solve the python in multiple inheritance, when the parent class has the same name function, the ambiguity of the problem

Let's look at an example below:

 import   Inspect  class   D:  pass  class   C (D):  pass  class   B (D):  pass  class   A (B, C):  pass  if  __name__  = =  "  __main__   " :  print  (Inspect.getmro (A))  

b and C inherit d   a inherit B and c  This is a simple multiple inheritance, see the output in Python3 below:

(<class'__main__. A';, <class'__main__. B';, <class'__main__. C';, <class'__main__. D';, <class'object'>)

The execution result is a->b->c->d

In Python3, the MRO algorithm uses a topological sort of a direction-free graph, where we use pruning methods to analyze:

As shown in: First to find the degree of 0 point A, because there is no class to inherit a, cut off a left and right side, get a->:

Next find the next 0 points (no classes inherit B and C after pruning), B and C in the degree of 0, according to the first left principle, cut off the branch of B, get A->b->:

Then we find that the point of 0 is C, then the branch of C is cut to get A->b->c

Finally get: The order of a->b->c->d

Next look at the execution results under Python2.7:

(<class__main__. A at 0x7f81a17ca1f0>, <class__main__. B at 0x7f81a17ca188>, <class__main__. D at 0x7f81a17ca0b8>, <class__main__. C at 0x7f81a17ca120>)

You can see that the execution result is a->b->d->c

This differs from the Python3 execution result because the Python2.7 MRO algorithm uses a depth-first search (child node order: left to right), so it is a->b->d->c

The multi-inheritance MRO algorithm of Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.