python MRO及c3算法

时间:2025-03-26 10:06:19

1. 了解python2和python3类的区别

python2在2.3之前使用的是经典类, 2.3之后, 使用的是新式类

2. 经典类的MRO 树形结构的深度优先遍历 -> 树形结构遍历

class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
class E:
pass
class F(D, E):
pass
class G(F, D):
pass
class H:
pass
class Foo(H, G):
pass

python MRO及c3算法

  

  从左到右,深度递归,一直到头再返回

    Foo -> H -> G -> D -> B -> A -> C -> E

3. 新式类的MRO C3算法

 拿第一项的第一位和 后面每项的除了第一位比较. 如果没有出现, 则该位元素算出如果出现了. 此时开始下一项的第一位继续和后面每一项的除了第一位比较:

用头和身体比较

 方法:   1. 拆分

   2. 合并

class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
class E(C, A):
pass
class F(D, E):
pass
class G(E):
pass
class H(G, F):
pass
L(H) = H + L(G) + L(F) + GF # ECA + DBECA  = HGFDBECAO
L(G) = G + L(E) + E # GECA
L(E) = E + L(C) + L(A) + CA # ECA
L(C) = C + L(A) + A # CA
L(A) = A
L(F) = F + L(D) + L(E) + DE # FDBECA
L(D) = D + L(B) + L(C) + BC # DBCA
L(B) = B + A + A # BA
与Python中使用H.__mro__运行的结果相同
(<class '__main__.H'>, <class '__main__.G'>, <class '__main__.F'>, <class '__main__.D'>, <

class '__main__.B'>, <class '__main__.E'>, <class '__main__.C'>, <class '__main__.A'>, 
<class 'object'>)
4. super() 找MRO顺序的下一个
class Base1:
def chi(self):
super().chi()
print("Base1") class Base2:
def chi(self):
super().chi()
print("Base2") class Base3:
def chi(self):
print("Base3") class Bar(Base1, Base2, Base3):
def chi(self):
print("Bar里chi1")
super(Bar, self).chi()
print("Bar里chi2") b = Bar()

  结果 :Bar里chi1,Base3,Base2,Base1,Bar里chi2