首页 > 解决方案 > 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++ 的头文件和源文件

标签: pythonincludemixinstype-hintingpython-typing

解决方案


在使用 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

推荐阅读