zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    audio元素
    获取页面中出现次数最多的三个标签以及出现次数
    vue ssr(server side rendering)
    python_2 python的编码声明
    python_1 python的编译过程
    bugs
    isPrototypeOf和 instanceof 的区别
    WebStorm 配置Git
    MongoDB 副本集搭建
    获取结算样式 getComputedStyle-currentStyle
  • 原文地址:https://www.cnblogs.com/gqtcgq/p/8081210.html
Copyright © 2011-2022 走看看