"使用mixins来实现抽象方法可以吗?"

2024-04-23 12:10:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

Tags: the代码概念defpassbeaxmixins
1条回答
网友
1楼 · 发布于 2024-04-23 12:10:21

是的,这正是mixin(或者更广泛地说,类)存在的目的。类应该封装与特定概念或目的相关联的所有特性(比如您的A和{},但也像您的X和{})。在

我相信你想得太多了。您可能知道如何使用类,mixin实际上只是被赋予了一个花哨名称的类,因为它们需要多重继承才能工作。(因为mixin并不总是能够独立运行的完整类;它们是可以附加到其他类的特性的集合。)类是关于关注点分离的。一个关注点-一个班级。为4个概念ABX和{}中的每一个实现一个类,然后根据需要组合它们(使用多重继承)。在

我强烈建议阅读What is a mixin, and why are they useful?。(当前)评价最高的答案很好地解释了mixin的存在正是针对这种情况。在

相关问题 更多 >