How do I dynamically add mixins as base classes without getting MRO errors?

后端 未结 3 1141
轻奢々
轻奢々 2021-02-20 17:39

Say I have a class A, B and C.

Class A and B are both mixin classes for Class C.

         


        
3条回答
  •  南旧
    南旧 (楼主)
    2021-02-20 18:06

    There is a simple workaround: Create a helper-class, with a nice name, like PluginBase. And use that the inherit of, instead of object.

    This makes the code more readable (imho) and it circumstances the bug.

    class PluginBase(object): pass
    class ServerBase(object): pass
    
    class pluginA(PluginBase): "Now it is clearly a plugin class"
    class pluginB(PluginBase): "Another plugin"
    
    class Server1(ServerBase, pluginA, pluginB): "This works"
    class Server2(ServerBase): pass
    Server2.__base__ += (PluginA,) # This also works
    

    As note: Probably you don't need the factory; it's needed in C++, but hardly in Python

提交回复
热议问题