Dynamic inheritance in Python

后端 未结 2 1950
攒了一身酷
攒了一身酷 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
        })
    

提交回复
热议问题