Skip to content

Latest commit

 

History

History
177 lines (116 loc) · 2.16 KB

113.md

File metadata and controls

177 lines (116 loc) · 2.16 KB

多重继承

多重继承,指的是一个类别可以同时从多于一个父类继承行为与特征的功能,Python 是支持多重继承的:

In [1]:

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 就使用了多重继承,它可以使用两个父类的方法:

In [2]:

leaf = MapleLeaf()

leaf.change("yellow")
print leaf.color

leaf.fall()
yellow
Plunk!

如果同时实现了不同的接口,那么,最后使用的方法以继承的顺序为准,放在前面的优先继承:

In [3]:

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

In [4]:

leaf = MapleLeaf()
leaf.fall()
Spalt!

In [5]:

class MapleLeaf(DeciduousLeaf, ColorChangingLeaf):
    pass

In [6]:

leaf = MapleLeaf()
leaf.fall()
Plunk!

事实上,这个顺序可以通过该类的 __mro__ 属性或者 mro() 方法来查看:

In [7]:

MapleLeaf.__mro__

Out[7]:

(__main__.MapleLeaf,
 __main__.DeciduousLeaf,
 __main__.ColorChangingLeaf,
 __main__.Leaf,
 object)

In [8]:

MapleLeaf.mro()

Out[8]:

[__main__.MapleLeaf,
 __main__.DeciduousLeaf,
 __main__.ColorChangingLeaf,
 __main__.Leaf,
 object]

考虑更复杂的例子:

In [9]:

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

调用顺序:

In [10]:

D.mro()

Out[10]:

[__main__.D, __main__.B1, __main__.B, __main__.C, __main__.A, object]