Dynamic inheritance in Python

后端 未结 2 1928
攒了一身酷
攒了一身酷 2020-11-27 17:39

Say I have 2 different implementations of a class

class ParentA:
    def initialize(self):
        pass

    def some_event(self):
        pass

    def orde         


        
相关标签:
2条回答
  • 2020-11-27 17:56

    Also, you can use type builtin. As callable, it takes arguments: name, bases, dct (in its simplest form).

    def initialize(self):
        self.initial_value = 1
    
    def some_event(self):
        # handle event
        order(self.initial_value)
    
    subclass_body_dict = {
        "initialize": initialize,
        "some_event": some_event
    }
    
    base_class = ParentA # or ParentB, as you wish
    
    MyCode = type("MyCode", (base_class, ), subclass_body_dict)
    

    This is more explicit than snx2 solution, but still - I like his way better.

    PS. of course, you dont have to store base_class, nor subclass_body_dict, you can build those values in type() call like:

    MyCode = type("MyCode", (ParentA, ), {
            "initialize": initialize,
            "some_event": some_event
        })
    
    0 讨论(0)
  • 2020-11-27 18:07

    Simply store the class-object in a variable (in the example below, it is named base), and use the variable in the base-class-spec of your class statement.

    def get_my_code(base):
    
        class MyCode(base):
            def initialize(self):
              ...
    
        return MyCode
    
    my_code = get_my_code(ParentA)
    
    0 讨论(0)
提交回复
热议问题