多重继承

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

In [1]:

  1. class Leaf(object):
  2. def __init__(self, color='green'):
  3. self.color = color
  4.  
  5. class ColorChangingLeaf(Leaf):
  6. def change(self, new_color='brown'):
  7. self.color = new_color
  8.  
  9. class DeciduousLeaf(Leaf):
  10. def fall(self):
  11. print "Plunk!"
  12.  
  13. class MapleLeaf(ColorChangingLeaf, DeciduousLeaf):
  14. pass

在上面的例子中, MapleLeaf 就使用了多重继承,它可以使用两个父类的方法:

In [2]:

  1. leaf = MapleLeaf()
  2.  
  3. leaf.change("yellow")
  4. print leaf.color
  5.  
  6. leaf.fall()
  1. yellow
  2. Plunk!

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

In [3]:

  1. class Leaf(object):
  2. def __init__(self, color='green'):
  3. self.color = color
  4.  
  5. class ColorChangingLeaf(Leaf):
  6. def change(self, new_color='brown'):
  7. self.color = new_color
  8. def fall(self):
  9. print "Spalt!"
  10.  
  11. class DeciduousLeaf(Leaf):
  12. def fall(self):
  13. print "Plunk!"
  14.  
  15. class MapleLeaf(ColorChangingLeaf, DeciduousLeaf):
  16. pass

In [4]:

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

In [5]:

  1. class MapleLeaf(DeciduousLeaf, ColorChangingLeaf):
  2. pass

In [6]:

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

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

In [7]:

  1. MapleLeaf.__mro__

Out[7]:

  1. (__main__.MapleLeaf,
  2. __main__.DeciduousLeaf,
  3. __main__.ColorChangingLeaf,
  4. __main__.Leaf,
  5. object)

In [8]:

  1. MapleLeaf.mro()

Out[8]:

  1. [__main__.MapleLeaf,
  2. __main__.DeciduousLeaf,
  3. __main__.ColorChangingLeaf,
  4. __main__.Leaf,
  5. object]

考虑更复杂的例子:

In [9]:

  1. class A(object):
  2. pass
  3.  
  4. class B(A):
  5. pass
  6.  
  7. class C(A):
  8. pass
  9.  
  10. class C1(C):
  11. pass
  12.  
  13. class B1(B):
  14. pass
  15.  
  16. class D(B1, C):
  17. pass

调用顺序:

In [10]:

  1. D.mro()

Out[10]:

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

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/08-object-oriented-programming/08.13-multiple-inheritance.ipynb