python基礎-多重繼承
阿新 • • 發佈:2019-01-06
繼承多個父類時,子類中使用哪個父類的屬性,跟class語句中這些父類的順序有關係,以前面的父類的屬性為準 ,在python中使用MRO(方法解析順序)這種演算法來查詢多重繼承下使用哪個父類的屬性
class B:
num = 78
class C:
num = 70
class A(B, C):
pass
print(A.__mro__)
print(A().num)
列印結果:
(<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>) 78
B類在C類前面,所以A繼承的num屬性是 num = 78
再看一個:
class F:
pass
class D(F):
name = 'aa'
class E(F):
name = 'ww'
class B(D):
num = 78
class C(E):
num = 70
class A(B, C):
pass
print(A.__mro__)
print(A().name)
列印結果:
(<class '__main__.A'>, <class '__main__.B'>, <class '__main__.D'>, <class '__main__.C'>, <class '__main__.E'>, <class '__main__.F'>, <class 'object'>) aa