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

Python类型注解:未提前声明类型的使用问题及类自引用报错

Python类内方法返回自身实例的类型注解报错问题

问题场景

在类的方法中用类型注解标注返回该类实例时,运行时会触发NameError,代码示例:

class Foo:
    def clone(self) -> Foo:
        return Foo()

运行时错误信息:

NameError: name 'Foo' is not defined

注:使用mypy静态检查时无此问题

解决方法

  • 字符串包裹类名(兼容Python 3.7及更早版本)
    类定义过程中自身尚未完成绑定,无法直接引用类名,用字符串包裹即可延迟解析:

    class Foo:
        def clone(self) -> 'Foo':
            return Foo()
    
  • 导入from __future__ import annotations(Python 3.7+)
    在文件顶部导入该特性后,所有类型注解会被当作字符串处理,运行时再解析:

    from __future__ import annotations
    
    class Foo:
        def clone(self) -> Foo:
            return Foo()
    
  • 使用typing.Self(Python 3.11+)
    Python 3.11专门引入Self类型,用于标注返回自身类实例的场景,语义更清晰:

    from typing import Self
    
    class Foo:
        def clone(self) -> Self:
            return Foo()
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:31:00