Python函数注释: class is not defined in method

标签 python class

我正在尝试为类的方法定义一个Python函数注释。该方法返回一个列表,其元素是该类的对象。我怎样才能做到这一点?

示例,

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

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

错误消息:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_18676/2160074272.py in <module>
----> 1 class Node:
      2     def __init__(self):
      3         self.children = []
      4 
      5     def get_children(self) -> list[Node]:

~\AppData\Local\Temp/ipykernel_18676/2160074272.py in Node()
      3         self.children = []
      4 
----> 5     def get_children(self) -> list[Node]:
      6         return self.children

NameError: name 'Node' is not defined

最佳答案

将类名放在引号中是一个完全可行的解决方案,但我想指出一种更适合 future 的解决方案。

有一个future import在表中,它将有效地自动将所有类型注释括在引号中,以避免这个问题。从 Python 3.10 开始,它将成为默认值,因此建议立即开始使用它。

from __future__ import annotations

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

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

关于Python函数注释: class is not defined in method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69924010/

相关文章:

java - 如何在外部类构造函数中创建内部类的实例

python - 如何在 Python 中实现持久计数器

python - 发现此代码片段中的未定义行为

python - python中的append()函数表现奇怪

PHP实例化子类

css - 我可以仅使用 CSS 添加类吗?

python - 为 BigQuery Python CLI 设置 GOOGLE_APPLICATION_CREDENTIALS

转换为字符串时, float 的 Python 精度丢失

java - 标识符预期错误 (Java)

python - 我们如何确定属性属于实例还是类?