python 多继承分析

5324阅读 0评论2012-12-28 datao0907
分类:Python/Ruby

多继承在针对派生类中的同名函数时,python 需要对其进行线性化(C3 Linearization),将继承图关系线性化。通过线性化,再依次查找类方法,直至找到该方法为止。线性化算法是python多继承的核心部分。线性化过程中,必须满足两个性质:

单调性

如果C从C'直接继承属性P(如图1),(C != C'),C'所有的父类(包含C')均在线性化中都是C的子列表。这样的话,C的线性化列表不用遍历C的所有继承体系,直接通过C的直接继承父类线性化列表获得(通过归并父类列表获得)。

一致性

直接父类的顺序通过用户来声明,父类线性化的顺序为从左到右。在进行线性化归并过程中,一致性主要保证类的局部优先级顺序,它定义了两个变量:
1) precC:类C的局部顺序
2) prec:局部顺序的并集

类C1,C2,C1 < precC C2 ===> C1 < prec C2,prec 为无环关系图。

通过上面的两个定义,引申出最终边的关系图。扩展关系 a

假设类的继承关系图为:

通过计算扩展关系 5 2 4 4

这样最终的关系图为:

线性化关系为:

点击(此处)折叠或打开

  1. L(7) = {'object'}
  2. L(4) = {'4','7'}
  3. L(5) = {'5','7'}
  4. L(6) = {'6','7'}
  5. L(2) = {'2','4','5','7','object'}
  6. L(3) = {'3','4','6','7','object'}
  7. L(1) = {'1','2','3','4','5','6','7','object'}
python 代码如下:

点击(此处)折叠或打开

  1. #! /usr/bin/env python
  2. #
  3. # multi inheritance view
  4. # /------ 7-------\
  5. # / | \
  6. # 4 - 5 6
  7. # \\ / /
  8. # 2-/\--- 3------/
  9. # \ /
  10. # 0,1
  11. #
  12. #

  13. class C7(object):
  14.     def test(self):
  15.         print 'test in C7'

  16. class C4(C7):
  17.     def test(self):
  18.         print 'test in C4'

  19. class C5(C7):
  20.     def test(self):
  21.         print 'test in C5'

  22. class C6(C7):
  23.     def test(self):
  24.         print 'test in C6'

  25. class C2(C4,C5):
  26.     def test(self):
  27.         print 'test in C2'

  28. class C3(C4,C6):
  29.     pass

  30. class C1(C2,C3):
  31.     pass

  32. class C0(C2,C3):
  33.     def test(self):
  34.         print 'test in C0'
  35.         super(C3,self).test()

  36. if __name__ == "__main__":
  37.     
  38.     c1 = C1()
  39.     c1.test()
  40.     c0 = C0()
  41.     c0.test()
  42.     print C7.__mro__
  43.     print C6.__mro__
  44.     print C5.__mro__
  45.     print C4.__mro__
  46.     print C3.__mro__
  47.     print C2.__mro__
  48.     print C1.__mro__
  49.     print C0.__mro__
输出结果为:

点击(此处)折叠或打开

  1. test in C2
  2. test in C0
  3. test in C4
  4. (<class '__main__.C7'>, <type 'object'>)
  5. (<class '__main__.C6'>, <class '__main__.C7'>, <type 'object'>)
  6. (<class '__main__.C5'>, <class '__main__.C7'>, <type 'object'>)
  7. (<class '__main__.C4'>, <class '__main__.C7'>, <type 'object'>)
  8. (<class '__main__.C3'>, <class '__main__.C4'>, <class '__main__.C6'>, <class '__main__.C7'>, <type 'object'>)
  9. (<class '__main__.C2'>, <class '__main__.C4'>, <class '__main__.C5'>, <class '__main__.C7'>, <type 'object'>)
  10. (<class '__main__.C1'>, <class '__main__.C2'>, <class '__main__.C3'>, <class '__main__.C4'>, <class '__main__.C5'>, <class '__main__.C6'>, <class '__main__.C7'>, <type 'object'>)
  11. (<class '__main__.C0'>, <class '__main__.C2'>, <class '__main__.C3'>, <class '__main__.C4'>, <class '__main__.C5'>, <class '__main__.C6'>, <class '__main__.C7'>, <type 'object'>)

上一篇:一些随机算法
下一篇:python 中的mixin特性