为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕的地8271018 2023-04-18 15:30:59
我创建了一个类似字典的自定义类来简化跨大型数据集的合并评估指标。此类实现了一种__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)
查看完整描述

1 回答

?
手掌心

TA贡献1942条经验 获得超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


查看完整回答
反对 回复 2023-04-18
  • 1 回答
  • 0 关注
  • 157 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信