python 中的mixin特性

6464阅读 0评论2012-12-29 datao0907
分类:Python/Ruby

python支持多继承后,但能否支持动态继承性质?在程序运行过程中,重定义类的继承,python是支持这种动态继承性质的。这也就是python中 的mixin,在定义类过程中改变类的继承顺序,继承类。当某个模块不能修改时,通过mixin方式可以动态添加该类的方法,动态改变类的原有继承体系。 弄懂了多继承,mixin特性就简单多了。 但需要注意mixin后的具体继承体系的改变。

  1. #!/usr/bin/env python

  2. import types

  3. def MixIn(pyClass,mixInClass,makeAncestor=0):

  4.     if makeAncestor:
  5.         pyClass.__bases__ = (mixInClass,) + pyClass.__bases__
  6.     elif mixInClass not in pyClass.__bases__:
  7.         pyClass.__bases__ = pyClass.__bases__ + (mixInClass,)
  8.     else:
  9.         pass

  10. class C1(object):
  11.     def test(self):
  12.         print 'test in C1'

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

  16. class C2(C1,C0MixIn):
  17.     def test(self):
  18.         print 'test in C2'

  19. class C0(C1):
  20.     pass

  21. if __name__ == "__main__":

  22.     print C0.__mro__
  23.     c1 = C0()
  24.     c1.test()
  25.     MixIn(C0,C0MixIn,1)
  26.     c0 = C0()
  27.     c0.test()
  28.     print C0.__mro__

  29.     print C2.__mro__
  30.     MixIn(C2,C0MixIn)
  31.     print C2.__mro__
运行结果如下: python mixin2.py

点击(此处)折叠或打开

  1. (<class '__main__.C0'>, <class '__main__.C1'>, <type 'object'>)
  2. test in C1
  3. test in C0MixIn
  4. (<class '__main__.C0'>, <class '__main__.C0MixIn'>, <class '__main__.C1'>, <type 'object'>)
  5. (<class '__main__.C2'>, <class '__main__.C1'>, <class '__main__.C0MixIn'>, <type 'object'>)
  6. (<class '__main__.C2'>, <class '__main__.C1'>, <class '__main__.C0MixIn'>, <type 'object'>)
参考资料

很详细的MixIn介绍:

上一篇:python 多继承分析
下一篇:linux文件系统日志(一)