Python类型注释:继承方法的返回类型

2024-06-25 23:32:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个自定义的类似字典的类,以简化跨大型数据集合并评估指标的过程。这个类实现了一个__add__方法来汇总各种度量

下面是我正在编写的代码的简化版本:

from __future__ import annotations
from typing import TypeVar, Dict


T = TypeVar('T', int, float)


class AddableDict(Dict[str, T]):
    def __add__(self, other: AddableDict[T]) -> AddableDict[T]:
        if not isinstance(other, self.__class__):
            raise ValueError()
        new_dict = self.__class__()
        all_keys = set(list(self.keys()) + list(other.keys()))
        for key in all_keys:
            new_dict[key] = self.get(key, 0) + other.get(key, 0)
        return new_dict


# AddableIntDict = AddableDict[int]
# this would work just fine, however I need to add a few additional methods


class AddableIntDict(AddableDict[int]):
    def some_int_specific_method(self) -> None:
        pass


def main() -> None:
    x = AddableIntDict()
    y = AddableIntDict()
    x['a'] = 1
    y['a'] = 3

    x += y  # breaks mypy

程序的最后一行中断mypy(0.782),并出现以下错误:

error: Incompatible types in assignment (expression has type "AddableDict[int]", variable has type "AddableIntDict")

这个错误对我来说是有道理的

当我将AddableIntDict定义为AddableDict[int]的类型别名时,代码运行良好,正如我在注释中所指出的,但是由于我需要根据字典值的类型添加其他方法,如some_int_specific_method所示,我不能简单地使用类型别名

有人能告诉我如何注释父类的__add__方法,以便它返回调用类的类型吗

(我正在使用Python 3.8.3)


Tags: 方法keyselfadd类型new字典def
1条回答
网友
1楼 · 发布于 2024-06-25 23:32:55

可以使用类型变量引用“类型self”。这将解析为调用方法的基类或子类的适当类型:

from typing import TypeVar, Dict


T = TypeVar('T', int, float)
AD = TypeVar('AD', bound='AddableDict')


class AddableDict(Dict[str, T]):
    def __add__(self: AD, other: AD) -> AD: ...


class AddableIntDict(AddableDict[int]):
    def some_int_specific_method(self) -> None: ...

x = AddableIntDict(a=1)
y = AddableIntDict(a=3)
x += y  # works for mypy and others

相关问题 更多 >