You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python父类方法返回子类的类型注解问题及正确实现方案

问题分析

你遇到的问题是因为TypeVar的使用方式不正确,导致mypy无法正确推断返回值类型。需要调整类型注解的方案,让父类和子类的类型关系清晰明确。

正确的类型注解方案

我们可以使用TypeVar结合Generic来实现类型安全的格式转换,同时明确每个方法的返回类型:

import abc
from typing import TypeVar, Generic

# 定义两个TypeVar分别代表FormatA和FormatB
TFormatA = TypeVar('TFormatA', bound='FormatA')
TFormatB = TypeVar('TFormatB', bound='FormatB')

class Format(abc.ABC):
    def to_formatA(self) -> 'FormatA':
        raise NotImplementedError()
    
    def to_formatB(self) -> 'FormatB':
        raise NotImplementedError()

class FormatA(Format):
    def to_formatA(self: TFormatA) -> TFormatA:
        return self
    
    def to_formatB(self) -> FormatB:
        return FormatB()

class FormatB(Format):
    def to_formatA(self) -> FormatA:
        return FormatA()
    
    def to_formatB(self: TFormatB) -> TFormatB:
        return self
方案说明
  • 对于返回自身的方法(如to_formatA在FormatA中),使用self: TFormatA的类型注解,让mypy知道返回的是当前类的实例(包括子类实例),避免类型不兼容错误。
  • 对于返回其他子类的方法,直接指定具体的返回类型(如FormatB),不需要使用TypeVar,因为返回的是固定类型的实例。
  • 父类中的方法直接声明返回具体子类类型,明确转换后的类型。

这样修改后,mypy就能正确识别所有方法的返回类型,不会再报之前的错误。

内容的提问来源于stack exchange,提问作者Papemax89

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 20:13:23