首页 > 解决方案 > 使用mixins实现抽象方法可以吗?

问题描述

我正在重构一些不太可重用并且有很多重复代码的代码。代码有两个类 A 和 B,它们扩展了抽象类 I。但是 A 和 B 的子类支持概念 X 和 Y,因此结果是具有概念 X 和 Y 的具体类 AX、AY、BX、BY 复制和粘贴进入每个。

所以我知道我可以在这里使用组合来委托对特性 X 和 Y 的支持,但这也需要构建这些对象等的代码,这就是我开始阅读 mixins 的原因,所以我想知道我的代码是否是一个好的解决方案

class I(ABC):
    @abstractmethod
    def doSomething():
        pass

class ICommon(ABC):
    @abstractmethod
    def doSomethingCommon():
        pass

class A(I, ICommon): 
    # the interface(s) illustrates what mixins are supported 
    # class B could be similar, but not necessarily with the same interfaces
    def doSomething():
        self.doSomethingCommon()
        ...

class XCommonMixin(object): 
    # feature X shared possibly in A and B
    # I have also split features X into much smaller concise parts, 
    # so the could be a few of these mixins to implement the different 
    # features of X
    def doSomethingCommon():
        return 42

class AX(XCommonMixin, A):
    pass 
    # init can be defined to construct A and bases if any as appropriate

标签: pythonoopmixinsabstract-methods

解决方案


是的,这正是 mixin(或更一般地,类)存在的目的。一个类应该封装与特定概念或目的相关的所有特性(比如你的Aand B,但也像你的Xand Y)。

我相信你多虑了。您可能知道如何使用类,而 mixin 实际上只是被赋予了一个花哨名称的类,因为它们需要多重继承才能工作。(因为 mixin 并不总是能够独立运行的完整类;它们是可以附加到其他类的特性的集合。)类是关于关注点分离的。一个问题 - 一节课。A为 4 个概念、和中的每一个实现一个类B,然后按照您认为合适的方式组合它们(使用多重继承)。XY

我强烈建议阅读什么是 mixin,它们为什么有用?. (当前)评分最高的答案很好地解释了 mixins 正是针对这种情况而存在的。


推荐阅读