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

Python类方法返回自身类实例列表的注解报NameError如何解决

报错原因

定义类内部方法的类型注解时,Node类本身还没有完成完整定义,解释器执行到list[Node]时还找不到Node这个名称,因此抛出NameError。

正确实现方式

下面是三种可直接使用的兼容方案,所有主流类型检查工具(如mypy)都可以正确识别:

方法1:使用future注解(Python 3.7+推荐)

在代码文件最顶部导入from __future__ import annotations,Python会自动将所有类型注解转为字符串延迟解析,不需要修改原有注解的写法:

from __future__ import annotations

class Node:
  def __init__(self):
    self.children = []

  def get_children(self) -> list[Node]:
    return self.children    

方法2:手动用字符串包裹类名

不需要额外导入依赖,直接把还未完成定义的类名放在引号中即可:

class Node:
  def __init__(self):
    self.children = []

  def get_children(self) -> list['Node']:
    return self.children    

方法3:使用Self类型(Python 3.11+适用)

Python 3.11及以上版本可以直接使用typing模块的Self指代当前类的实例,后续修改类名时不需要同步修改注解内容,通用性更强:

from typing import Self

class Node:
  def __init__(self):
    self.children = []

  def get_children(self) -> list[Self]:
    return self.children    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:45:04