本文最后更新于 258 天前,其中的信息可能已经过时,如有错误请发送邮件到wuxianglongblog@163.com
多重继承
多重继承,指的是一个类别可以同时从多于一个父类继承行为与特征的功能,Python
是支持多重继承的:
class Leaf(object):
def __init__(self, color='green'):
self.color = color
class ColorChangingLeaf(Leaf):
def change(self, new_color='brown'):
self.color = new_color
class DeciduousLeaf(Leaf):
def fall(self):
print "Plunk!"
class MapleLeaf(ColorChangingLeaf, DeciduousLeaf):
pass
在上面的例子中, MapleLeaf
就使用了多重继承,它可以使用两个父类的方法:
leaf = MapleLeaf()
leaf.change("yellow")
print leaf.color
leaf.fall()
yellow
Plunk!
如果同时实现了不同的接口,那么,最后使用的方法以继承的顺序为准,放在前面的优先继承:
class Leaf(object):
def __init__(self, color='green'):
self.color = color
class ColorChangingLeaf(Leaf):
def change(self, new_color='brown'):
self.color = new_color
def fall(self):
print "Spalt!"
class DeciduousLeaf(Leaf):
def fall(self):
print "Plunk!"
class MapleLeaf(ColorChangingLeaf, DeciduousLeaf):
pass
leaf = MapleLeaf()
leaf.fall()
Spalt!
class MapleLeaf(DeciduousLeaf, ColorChangingLeaf):
pass
leaf = MapleLeaf()
leaf.fall()
Plunk!
事实上,这个顺序可以通过该类的 __mro__
属性或者 mro()
方法来查看:
MapleLeaf.__mro__
(__main__.MapleLeaf,
__main__.DeciduousLeaf,
__main__.ColorChangingLeaf,
__main__.Leaf,
object)
MapleLeaf.mro()
[__main__.MapleLeaf,
__main__.DeciduousLeaf,
__main__.ColorChangingLeaf,
__main__.Leaf,
object]
考虑更复杂的例子:
class A(object):
pass
class B(A):
pass
class C(A):
pass
class C1(C):
pass
class B1(B):
pass
class D(B1, C):
pass
调用顺序:
D.mro()
[__main__.D, __main__.B1, __main__.B, __main__.C, __main__.A, object]