python - Python中的动态继承

标签 python inheritance

假设我有 2 个不同的类实现

class ParentA:
    def initialize(self):
        pass

    def some_event(self):
        pass

    def order(self, value):
        # handle order in some way for Parent A


class ParentB:
    def initialize(self):
        pass

    def some_event(self):
        pass

    def order(self, value):
        # handle order in another for Parent B

我怎样才能动态地让一些第三类继承自 ParentAParentB 基于这样的东西?

class MyCode:
    def initialize(self):
        self.initial_value = 1

    def some_event(self):
        # handle event
        order(self.initial_value)


# let MyCode inherit from ParentA and run
run(my_code, ParentA)

最佳答案

只需将类对象存储在一个变量中(在下面的示例中,它被命名为 base ),并在您的 class 的基类规范中使用该变量声明。

def get_my_code(base):

    class MyCode(base):
        def initialize(self):
          ...

    return MyCode

my_code = get_my_code(ParentA)

关于python - Python中的动态继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21060073/

相关文章:

python - 设置matplotlib中y轴系数的颜色

python - python 函数中的本地列表

python - 从 Spark 连接到 HANA

r - 如何使一个 S4 类从另一个 S4 类正确继承?

entity-framework - 域实体跟踪数据的最佳实践?基类还是组合?

javascript constructor.prototype继承另一个constructor.prototype

python - 检测应用层协议(protocol),python?

python - 需要帮助从 csv excel 文件创建字典

java - java 中的 protected 访问不起作用

c++ - protected 构造函数与纯虚拟析构函数