【发布时间】:2018-09-23 16:31:10
【问题描述】:
我正在重构一些不太可重用并且有很多重复代码的代码。代码有两个类 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
【问题讨论】:
-
在 6 个月内,有人需要阅读代码(甚至是未来的你)......他们会理解吗?如果您认为他们会这样做,请继续实施您的复杂解决方案。然后在 6 个月后回来看看您是否正确。
标签: python oop mixins abstract-methods