python - Python mixins 中的主类类型
问题描述
我有一个分为混合类的类:
class MyObject(MyObjectFilesMixin, MyObjectProcessingMixin, ...):
def __init__(self, value):
self.value = self.preprocess(value)
一个 mixin 看起来像这样:
class MyObjectFilesMixin:
def load_from_file(cls, filename):
return ...
现在我想在类和 mixins 中添加类型:
class MyObjectFilesMixin:
def load_from_file(cls, filename: str) -> MyObject:
return ...
class MyObjectProcessingMixin:
def preprocess(self: MyObject, value: bytes):
return value # logic is omitted
def append(self: MyObject, other: MyObject):
self.value += other.value
但它会导致循环链接。当然我可以创建一些MyObjectBase
(遵循依赖倒置原则),这样它MyObject
也将继承这个类,并且 mixins 会将它用作参数/返回类型,但这无论如何都会导致错误的类型。可以修吗??
我错过了很多来自 C++ 的头文件和源文件
解决方案
在使用 mixin 继承的情况下,协议和结构子类型和TYPE_CHECKING可以通过避免循环导入来帮助成功地键入类,它可能看起来像这样:
# my_object.py
from mixins import ProcessingMixin
class MyObject(ProcessingMixin):
def __init__(self, value):
self.value = self.preprocess(value)
def some_process(self, value) -> bytes:
...
# mixins.py
from typing import Protocol, TYPE_CHECKING
if TYPE_CHECKING:
from my_object import MyObject
class ValueObjectProto(Protocol):
"""Protocol for value processing methods."""
value: bytes
def preprocess(self, value: bytes) -> bytes: ...
def some_process(self, value) -> bytes: ...
class MyObjectFilesMixin:
def load_from_file(cls, filename: str) -> MyObject:
return cast(Type[MyObject], cls)(1)
class ProcessingMixin:
def preprocess(self: ValueObjectProto, value: bytes) -> bytes:
value = self.some_process(value)
return value
def append(self: ValueObjectProto, other: ValueObjectProto) -> None:
self.value += other.value
推荐阅读
- javascript - 运行 https:/username/github.io/index.html 时出现 ERR_ABORTED 404 错误
- java - Spring Boot 控制器如何与其他包中的对象通信?
- satellite - 我想在地图上显示陆地卫星图像(网络应用程序)
- rust - 如何在 Actix-Web 中为多种方法使用路由属性宏
- google-sheets - Google 表格导入多个 HTML 表格图像
- sql - postgres 在 JSON 数组中提取多个值
- c# - 从动态对象列表中删除对象
- .net - 如何在特定级别的文件夹和子文件夹中搜索“文件夹”
- javascript - 为什么每次触发事件时这个数组都没有保存推送的元素?
- ruby-on-rails - 找不到 heroku.com 页面 - 应用程序是 rails api