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

Python中类方法作为工厂方法时,如何编写返回值类型提示?

解决Python类方法返回类型提示报错问题

在类定义内部直接用-> Example作为返回类型会报错,核心原因是此时类Example还未完成完整定义,类型检查器无法识别这个尚未完全创建的类对象。以下是三种可行的解决方法:

  • 方案1:使用字符串字面量(兼容所有Python版本)
    把返回类型写成字符串形式的"Example",让类型检查器延迟解析这个类名,等类定义完成后再识别:

    from typing import List
    
    class Example:
        @classmethod
        def build_class_instance(cls, fixed_inputs: List[str], unchanged_args) -> "Example":
            new_vars = f(fixed_inputs)  # 假设f是已定义的处理函数
            return Example(new_vars, unchanged_args)
    
  • 方案2:导入__future__的annotations(Python 3.7+)
    在文件顶部添加from __future__ import annotations,这会让所有类型注解自动以字符串形式存储,无需手动加引号:

    from __future__ import annotations
    from typing import List
    
    class Example:
        @classmethod
        def build_class_instance(cls, fixed_inputs: List[str], unchanged_args) -> Example:
            new_vars = f(fixed_inputs)
            return Example(new_vars, unchanged_args)
    

    注:Python 3.10+中该特性成为默认行为,但显式导入仍可在3.7-3.9版本中正常使用。

  • 方案3:使用Self类型(Python 3.11+)
    从typing模块(Python 3.11+)或types模块(Python 3.12+)导入Self,直接用它表示当前类的实例类型,语义更明确,同时建议用cls替代硬编码的类名,适配子类继承场景:

    from typing import List, Self
    
    class Example:
        @classmethod
        def build_class_instance(cls, fixed_inputs: List[str], unchanged_args) -> Self:
            new_vars = f(fixed_inputs)
            return cls(new_vars, unchanged_args)
    

内容的提问来源于stack exchange,提问作者An old man in the sea.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:01:23