Programmer's Python - Multiple Inheritance |
Written by Mike James | ||||
Monday, 15 October 2018 | ||||
Page 3 of 3
The C3 Algorithm and the mroTo make things easier we have to linearize the inheritance so that it looks like the chain of superclasses that we have in single inheritance. The idea is that you need to create an order that the classes are searched to find an attribute in the mro. You can see that some of the classes are more basic than others – they are naturally earlier in the inheritance chain. In Python 2 a simple left to right depth first method was used, but in Python 3 (and 2.3 on for new classes) the C3 method which has much better properties is used. For example in: It is reasonable that B and C would have more attributes than A as they are derived from A. In this sense A comes earlier in the inheritance chain and B and C should be searched first for attributes, and then A. Our first principle is that no base class should appear in the mro before its child classes. That is A, should not appear before B or C. Clearly A should only be searched once and this is the second principle: no duplicate classes in the mro. Which of B or C should be searched first? There is no absolute answer to this but Python uses the idea that the order that you specify classes should be important. That is, the classes should appear in the mro in the same order that they appear in the class definition reading left to right. So if you are specifying: class D(C,B) then C should come before B in the mro: D → C → B → A but if you define: class D(B,C) then B should come before C: D → B → C → A The final principle is the most sophisticated – the mro should be monotonic. That is, if C1 precedes C2 in the mro of C, then this is true in the mro of any subclass of C. That is, adding a class to the mro doesn’t change the order of what you already have. It might insert a class between two existing classes, but it never changes the order of two classes. This makes any decisions you have made based on the mro for class C valid for a class derived from C. To sum up, the C3 algorithm produces an mro that:
The C3 algorithm was invented as part of the Dylan language and it is used in Perl as well as Python. Notice that there are inheritance graphs that cannot be linearized and in this case Python will display an error message. The correct response to this is to consider what is wrong with the proposed inheritance and change it. You should only ever use multiple inheritance that is linearizable by the C3 or a similar algorithm to give the desirable properties listed earlier. Computing the C3 mroFinal version in book. Getting to Know LinearizationFinal version in book. Calling Super Cooperative Multiple InheritanceFinal version in book. The Dwindling Parameter PatternFinal version in book.
Summary
Programmer's Python
|
||||
Last Updated ( Monday, 15 October 2018 ) |