Chinaunix首页 | 论坛 | 博客

分类: Python/Ruby

2012-12-29 16:03:16

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介绍:http://www.linuxjournal.com/node/4540/print

阅读(4805) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~
评论热议
请登录后评论。

登录 注册