python的继承,多继承,经典类的MRO,新式类的MRO,C3算法,super
Posted 冒蓝火的加特林哒哒哒
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python的继承,多继承,经典类的MRO,新式类的MRO,C3算法,super相关的知识,希望对你有一定的参考价值。
#继承 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__)#得到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)
class haha(object):pass
class base(object):pass
class foo(base,haha):pass
print(foo.__bases__)#获取当前类的父类返回一个元组(base,haha)
以上是关于python的继承,多继承,经典类的MRO,新式类的MRO,C3算法,super的主要内容,如果未能解决你的问题,请参考以下文章