Python中的动态继承

所谓动态继承,是指代码运行时再决定某个类的父类。某些场景下会用到,比如threading.Thread和multiprocessing.Process这两个类有很多同名的接口,可以实现某个子类动态继承这两个类中的某一个,以便测试多线程或多进程的效率问题。

1:使用工厂函数

def createClass(cls):
    class CustomizedClass(cls): 
        .......
    return CustomizedClass
 
ClassList = createClass(list)
print(ClassList.__bases__) #prints the parent class names for ClassList        
 
instanceClassList = ClassList([1, 2, 3]) #object of ClassList created
 
ClassDict = createClass(dict)    
print(ClassDict.__bases__)    #prints the parent class names for ClassDict
 
instanceClassDict = ClassDict({'a':1, 'b':2}) #object of ClassDict created

 

 

2:使用条件表达式

class A:
    #code for the class A...
class B:
    #code for the class B...
class MyClass( A if (condition) else B):
    #code for the derived class MyClass

 

 

参考:

https://www.quora.com/In-Python-is-it-possible-to-decide-which-class-to-inherit-during-runtime

https://stackoverflow.com/questions/21060073/dynamic-inheritance-in-python

https://stackoverflow.com/questions/17599850/dynamically-choosing-class-to-inherit-from

 

posted @ 2017-12-21 16:25  gqtc  阅读(4406)  评论(0编辑  收藏  举报