说我有一个类的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类继承自一个ParentA或ParentB基于此类的东西?
ParentA
ParentB
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语句的基类规范中使用该变量。
base
class
def get_my_code(base): class MyCode(base): def initialize(self): ... return MyCode my_code = get_my_code(ParentA)