python - 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)
解决方案
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
推荐阅读
- javascript - Cordova cammands 无法正确执行,而是永远挂起
- laravel - 在刀片组件中定义 vue 应用
- java - 为什么 Spring Security 禁止特定资源而不考虑角色?
- node.js - Passport.js 中的 Google 策略是否随着 Google+ 的结束而弃用
- python-3.x - Pytest - 测试用例执行顺序
- django - 如何从另一个场景中的一个步骤执行一个场景?
- sql - 不使用分析进行分组的自加入
- php - JWT 过期。哪种方法最好?
- python - 如何通过带有条件的键对二维列表进行分组?
- condor - 如何为 isilon 存储设置用户吞吐量限制