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

后端 未结 3 1143
轻奢々
轻奢々 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 17:51

    Think of it this way -- you want the mixins to override some of the behaviors of object, so they need to be before object in the method resolution order.

    So you need to change the order of the bases:

    class C(A, B, object):
        pass
    

    Due to this bug, you need C not to inherit from object directly to be able to correctly assign to __bases__, and the factory really could just be a function:

    class FakeBase(object):
        pass
    
    class C(FakeBase):
        pass
    
    def c_factory():
        for base in (A, B):
            if base not in C.__bases__:
                C.__bases__ = (base,) + C.__bases__
        return C()
    

提交回复
热议问题