gpt4 book ai didi

Python 类型注解 : return type of inherited method

转载 作者:行者123 更新时间:2023-12-05 02:05:46 24 4
gpt4 key购买 nike

我创建了一个类似字典的自定义类来简化跨大型数据集的合并评估指标。此类实现了一个 __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),并出现以下错误:

错误:赋值中的类型不兼容(表达式的类型为“AddableDict[int]”,变量的类型为“AddableIntDict”)

这个错误对我来说很有意义。

如我的评论所述,当我将 AddableIntDict 定义为 AddableDict[int] 的类型别名时,代码工作正常,但是因为我需要添加其他方法,具体取决于关于字典值的类型,如 some_int_specific_method 所示,我不能简单地使用类型别名。

谁能指出正确的方向,让我知道如何注释父类的 __add__ 方法,以便它返回调用类的类型?

(我使用的是 Python 3.8.3)

最佳答案

可以使用类型变量来引用“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

关于Python 类型注解 : return type of inherited method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63178106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com