我正在尝试为类的方法定义一个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/