python - 使用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
解决方案
是的,这正是 mixin(或更一般地,类)存在的目的。一个类应该封装与特定概念或目的相关的所有特性(比如你的A
and B
,但也像你的X
and Y
)。
我相信你多虑了。您可能知道如何使用类,而 mixin 实际上只是被赋予了一个花哨名称的类,因为它们需要多重继承才能工作。(因为 mixin 并不总是能够独立运行的完整类;它们是可以附加到其他类的特性的集合。)类是关于关注点分离的。一个问题 - 一节课。A
为 4 个概念、和中的每一个实现一个类B
,然后按照您认为合适的方式组合它们(使用多重继承)。X
Y
我强烈建议阅读什么是 mixin,它们为什么有用?. (当前)评分最高的答案很好地解释了 mixins 正是针对这种情况而存在的。
推荐阅读
- javascript - sequelize.sync():NUMBER 附近的 SQL 语法错误
- ssis - 日期格式如何跨 SSIS、SQL 和所有变量设置工作?
- python - Socket 分片接收数据
- c# - clrmd - 使用 DataTarget.CreateSnapshotAndAttach 后获取 System.Runtime.InteropServices.SEHException
- swiftui - SwiftUI 绑定错误:为什么这不起作用?
- mysql - MySQL 将表转换为 JSON 文件
- python - 无法将大小为 85696 的数组重塑为形状 (85696,1,256,256)
- asp.net-mvc - 如何在模态引导程序中调整表格
- javascript - 从 id 数组中删除用户 id
- ios - CoreBluetooth 中央在指定服务时未发现任何外围设备