标签:bsp 深度优先 继承 foo func 深度 inf image 9.png
#继承 class JiaoFu: def qd(self): print("教父带你祈祷") class Fu: def msj(self): print("alex喜欢msj") class Zi(Fu, JiaoFu): def dbj(self): print("刘伟喜欢大宝剑") z = Zi() z.msj() z.dbj() z.qd() class Base1: # Base1 object def func(self): print("娃哈哈") class Base2: def func(self): print("雪碧") class Foo(Base1, Base2): # Foo, Base1, Base2 pass f = Base1() f.func() # 雪碧, 娃哈哈 #经典类的MRO,深度优先 class A: pass class B: pass class C: pass class D: pass class E(A, C): pass class F(B, D): pass class G(E, F): pass # GEACFBD # #新式类的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 G(E): pass class H(G, F): pass print(H.__mro__) # H的MRO: ?? # 拆 # L(H)= H + L(G) + L(F) -> H + (GECA) + (FDBECA) -> HGFDBECA (MRO) # # # L(G) = G + L(E) -> G +(ECA) -> GECA # # L(F) = F + L(D) + L(E) -> F +(DBCA) + (ECA) -> FDBECA # # # L(E) = E + L(C) + L(A) -> E + (CA) + A -> ECA # # L(D) = D + L(B)+ L(C) -> D + (BA) + (CA) -> DBCA # # # L(c) = C + A CA # # L(B) = B + A BA # # # L(A) = A #实例 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 N: pass class O: pass class M(N, O): pass class G(E, M): pass class H(G, F): pass print(H.__mro__) # H的MRO ‘‘‘ L(H) = H + L(G) + L(F) -> H + (MNO) + () -> H G F D B E C A M N O L(G) = G + L(E) + L(M) -> G + (ECA) + (MNO) -> GECAMNO L(F) = F + L(D) + L(E) -> F + (DBCA) + (ECA) -> FDBECA L(E) = E + (CA) + A -> ECA L(M) = M + N + O -> MNO L(D) = D + (BA) + (CA) -> DBCA H G F D B E C A M N O ‘‘‘
# MRO + super ?试题 class Init(object): def __init__(self, v): print("init") self.val = v class Add2(Init): def __init__(self, val): print("Add2") super(Add2, self).__init__(val) print(self.val) # 5 self.val += 2 # 7 class Mult(Init): def __init__(self, val): print("Mult") super(Mult, self).__init__(val) self.val *= 5 class HaHa(Init): def __init__(self, val): print("哈哈") super(HaHa, self).__init__(val) self.val /= 5 class Pro(Add2,Mult,HaHa): # pass class Incr(Pro): def __init__(self, val): super(Incr, self).__init__(val) self.val += 1 print(Incr.__mro__) # p = Incr(5) # MRO: Incr Pro Add2 Mult HaHa Init # # 一个对象. p : val: 8 # print(p.val) c = Add2(2) # MRO: ADD2 INIT print(c.val)
python的继承,多继承,经典类的MRO,新式类的MRO,C3算法,super
标签:bsp 深度优先 继承 foo func 深度 inf image 9.png
原文地址:https://www.cnblogs.com/PythonMrChu/p/9733684.html