python之继承
程序员文章站
2022-05-02 09:19:42
1.经典MRO : 树形结构的深度遍历优先 - > 树形结构遍历 流程图: 类的MRO: Foo -> H -> I-> J-> B-> A-> C-> K-> G-> F-> D-> E 2.新式类的MRO C3算法 C3算法: ......
1.经典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 i: pass class j(b, c): pass class k(a): pass class h(i, j, k): pass class foo(h, g): pass
流程图:
类的mro: foo -> h -> i-> j-> b-> a-> c-> k-> g-> f-> d-> e
2.新式类的mro c3算法
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 m:
pass
class n(m):
pass
class p(e, a):
pass
class x:
pass
class q(p, n, x):
pass
class g(q, f):
pass
class h(g, f):
pass
print(h.__mro__)
'''
(<class '__main__.h'>, <class '__main__.g'>, <class '__main__.q'>, <class '__main__.p'>,
<class '__main__.f'>, <class '__main__.d'>, <class '__main__.b'>, <class '__main__.e'>,
<class '__main__.c'>, <class '__main__.a'>, <class '__main__.n'>, <class '__main__.m'>,
<class '__main__.x'>, <class 'object'>)
'''
c3算法:
l(h) = h + l(g) + l(f) + gf # hgqpfdbecanmx
l(g) = g + l(q) + l(f) + qf # gqpfdbecanmx
l(q) = q + l(p) + l(n) + x + pnx # qpecanmx
l(p) = p + l(e) + a + ea # peca
l(e) = e + l(c) + a + ca # eca
l(c) = c + a + a # ca
l(n) = n + m # nm
l(f) = f + l(d) + l(e) + de # fdbeca
l(d) = d + l(b) + l(c) + bc # dbca
加法:merge(), 拿第一项的第一位和 后面每项的除了第一位比较. 如果没有出现, 则该位元素算出
如果出现了. 此时开始下一项的第一位继续和后面每一项的除了第一位比较:
中心思想:用头和后面身体比较