python支持
多继承后,但能否支持动态继承性质?在程序运行过程中,重定义类的继承,python是支持这种动态继承性质的。这也就是python中
的mixin,在定义类过程中改变类的继承顺序,继承类。当某个模块不能修改时,通过mixin方式可以动态添加该类的方法,动态改变类的原有继承体系。
弄懂了多继承,mixin特性就简单多了。
但需要注意mixin后的具体继承体系的改变。
- #!/usr/bin/env python
- import types
- def MixIn(pyClass,mixInClass,makeAncestor=0):
- if makeAncestor:
- pyClass.__bases__ = (mixInClass,) + pyClass.__bases__
- elif mixInClass not in pyClass.__bases__:
- pyClass.__bases__ = pyClass.__bases__ + (mixInClass,)
- else:
- pass
- class C1(object):
- def test(self):
- print 'test in C1'
- class C0MixIn(object):
- def test(self):
- print 'test in C0MixIn'
- class C2(C1,C0MixIn):
- def test(self):
- print 'test in C2'
- class C0(C1):
- pass
- if __name__ == "__main__":
- print C0.__mro__
- c1 = C0()
- c1.test()
- MixIn(C0,C0MixIn,1)
- c0 = C0()
- c0.test()
- print C0.__mro__
- print C2.__mro__
- MixIn(C2,C0MixIn)
- print C2.__mro__
运行结果如下: python mixin2.py
- (<class '__main__.C0'>, <class '__main__.C1'>, <type 'object'>)
- test in C1
- test in C0MixIn
- (<class '__main__.C0'>, <class '__main__.C0MixIn'>, <class '__main__.C1'>, <type 'object'>)
- (<class '__main__.C2'>, <class '__main__.C1'>, <class '__main__.C0MixIn'>, <type 'object'>)
- (<class '__main__.C2'>, <class '__main__.C1'>, <class '__main__.C0MixIn'>, <type 'object'>)
参考资料
很详细的MixIn介绍:
阅读(6470) | 评论(0) | 转发(0) |