小编典典

Python中的动态继承

python

说我有一个类的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

如何动态地让某个3rd类继承自一个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)

阅读 220

收藏
2020-12-20

共1个答案

小编典典

只需将类对象存储在变量中(在下面的示例中,其名为base),然后在class语句的基类规范中使用该变量。

def get_my_code(base):

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

    return MyCode

my_code = get_my_code(ParentA)
2020-12-20