# Python Method Resolution Order

2017-03-21

## 定义

1. The list of the ancestors of a class C, including the class itself, ordered from the nearest ancestor to the furthest, is called the class precedence list or the linearization of C.
2. The Method Resolution Order (MRO) is the set of rules that construct the linearization. In the Python literature, the idiom “the MRO of C” is also used as a synonymous for the linearization of the class C.
3. A MRO is monotonic when the following is true: if C1 precedes C2 in the linearization of C, then C1 precedes C2 in the linearization of any subclass of C.

## 经典类

class A: pass

class B(A): pass

class C(A): pass

class D(B, C): pass


## 新式类

Python 的新式类基于 C3 Linearization 算法，考虑一个类 C 继承自基于 B1, B2, …, BN，那么类 C 的线性化结果 L[C] 计算如下：

the linearization of C is the sum of C plus the merge of the linearization of the parents and the list of the parents.

take the head of the first list, i.e L[B1][0]; the head is a good head if it is not in the tail of any other lists, then add it to the linearization of C and remove it from all of the lists in the merge, otherwise look at the head of the next list and take it, if it is a good head. Repeat the operation until all the class are removed ot it is impossible to find a good head. In later case, it it impossible to construct the merge, Python will refuse to create the class C and will raise an exception.

### 例一


O = object

class F(O): pass

class E(O): pass

class D(O): pass

class C(D, F): pass

class B(D, E): pass

class A(B, C): pass



O，D，E 和 F 的线性化计算都比较简单：

### 例二

A = Object

class B(A): pass

class C(A): pass

class D(B, C): pass


### 例三

O = object

class X(O): pass

class Y(O): pass

class A(X, Y): pass

class B(Y, X): pass

class C(A, B): pass



TypeError: Cannot create a consistent method resolution
order (MRO) for bases X, Y