當類有多個超類筒饰,而且超類中有相同的方法時铐尚,繼承順序就很重要胧奔,如下:
class A
(def save(self):...) # A 中有self方法
/ \
/ \
class B class C
(def save(self):...) # B 和 C 中都繼承 A皇拣,只有C中重寫save方法
\ /
\ /
\ /
class D # 繼承 B 和 C
舊式類
在舊式類中穷吮,會根據深度優(yōu)先(depth-first
)的順序來繼承逻翁,由左至右依次查找save()
方法,D -> B -> A ->C,當查到方法時捡鱼,立刻放回八回,不在繼續(xù)查找。
# 例:
class A:
def __init__(self):
print 'it is A'
def save(self):
print 'save method from A'
class B(A):
def __init__(self):
print 'it is B'
class C(A):
def __init__(self):
print 'it is C'
def save(self):
print 'save method from C'
class D(B, C):
def __init__(self):
print 'it is D'
d = D()
d.save()
# 結果 ==》
it is D
save method from A # 根據上邊的順序驾诈,查到A中的save方法缠诅,即返回。
新式類
新式類中會根據方法解析順序(MRO)來進行搜索乍迄,廣度優(yōu)先管引,當查到對應方法屬性時,立即返回就乓,不再繼續(xù)查找汉匙。
__mro__
屬性拱烁,標記了python繼承層次中父類的查找順序生蚁,Python的多重繼承機制就是按照__mro__
的順序進行查找,一旦找到對應屬性戏自,則查找馬上返回邦投。
# 例 1
class A(object):
def __init__(self):
print 'it is A'
def save(self):
print 'save method from A'
class B(A):
def __init__(self):
print 'it is B'
class C(A):
def __init__(self):
print 'it is C'
def save(self):
print 'save method from C'
class D(B, C):
def __init__(self):
print 'it is D'
print D.__mro__
d = D()
d.save()
# 結果==》
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
it is D
save method from C
# 例 2
class A(object):
def save(self):
print ('save A')
class B(object):
def save(self):
print ('save B')
class C(object):
def save(self):
print ('save C')
class D(B,C,A):
pass
print D.__mro__
cla = D()
cla.save()
# 結果
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
save B
# 例 3
class B(object):
def foo(self):
print ('foo B')
def bar(self):
print 'bar B'
class A(object):
def foo(self):
print ('foo A')
class C1(A, B):
pass
class C2(A, B):
def bar(self):
print 'bar C2'
class D(C1, C2):
pass
print D.__mro__
d = D()
d.foo()
d.bar()
# 結果
(<class '__main__.D'>, <class '__main__.C1'>, <class '__main__.C2'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>)
foo A
bar C2