亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 215 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號