当类有多个超类,而且超类中有相同的方法时,继承顺序就很重要,如下:
class A
(def save(self):...) # A 中有self方法
/ \
/ \
class B class C
(def save(self):...) # B 和 C 中都继承 A,只有C中重写save方法
\ /
\ /
\ /
class D # 继承 B 和 C
旧式类
在旧式类中,会根据深度优先(depth-first
)的顺序来继承,由左至右依次查找save()
方法,D -> B -> A ->C,当查到方法时,立刻放回,不在继续查找。
# 例:
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)来进行搜索,广度优先,当查到对应方法属性时,立即返回,不再继续查找。
__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
网友评论