希望我不会漏掉任何重要的东西。我非常简化的情况如下:
在我的领域中,我有一些定义的数据结构:
@dataclass class Model: var_1: str var_2: str class Book(Model): ... class Page(Model): ...
我想有两个抽象步骤来定义数据的处理方式,比如:
PARAMETERS = TypeVar("PARAMETERS", bound=Model) RESULT = TypeVar("RESULT", bound=Model) class Finder(Generic[PARAMETERS, RESULT], metaclass=abc.ABCMeta): def run(self, parameters_dict: Dict[str, str]) -> RESULT: parameters = self.parse_parameters(parameters_dict) return self.do_stuff(parameters) @abc.abstractmethod def parse_parameters(self, parameters_dict: Dict[str, str]) -> PARAMETERS: ... @abc.abstractmethod def do_stuff(self, parameters: PARAMETERS) -> RESULT: ... BookParameter = TypeVar("BookParameter", bound=Book) BookResult = TypeVar("BookResult", bound=Page) class BookFinder(Generic[BookParameter, BookResult], Finder[BookParameter, BookResult], abc.ABC): def parse_parameters(self, parameters_dict: Dict[str, str]) -> BookParameter: return Book(**parameters_dict) @abc.abstractmethod def do_stuff(self, parameters: BookParameter) -> BookResult: ...
然后像这样使用:
class ItalianBookFinder(BookFinder[Book, Page]): def do_stuff(self, parameters: Book) -> Page: # define this class LatinBook(Book): var_3: str class LatinBookFinder(BookFinder[LatinBook, Page]): def parse_parameters(self, parameters_dict: Dict[str, str]) -> LatinBook: # define both this def do_stuff(self, parameters: LatinBook) -> Page: # and this too class EnglishPageFinder(PageFinder[EnglishPage, PageFinderResult]): ....
(我省略了RESULT
部分,但类似于PARAMETERS
,文本太长了)
但当我在代码上运行mypy检查时,我得到了错误:
Incompatible return value type (got "Book", expected "BookParameter") [return-value]
这让我觉得我做得不对。我可能完全遗漏了一些重要的部分,或者这里有设计缺陷,如果有人知道我会很乐意接受任何输入。谢谢。