我創建了一個類似字典的自定義類來簡化跨大型數據集的合并評估指標。此類實現了一種__add__方法來匯總各種指標。這是我正在處理的代碼的簡化版本:from __future__ import annotationsfrom typing import TypeVar, DictT = 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 methodsclass AddableIntDict(AddableDict[int]): def some_int_specific_method(self) -> None: passdef 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)
Python類型注解:繼承方法的返回類型
慕的地8271018
2023-04-18 15:30:59