我来自java后台,学习python。我正在尝试创建一个python类(使用静态类型),包含相同类的成员。
mynode.py
class MyNode():
def __init__(self, id: str=None, child_node: MyNode=None):
self._id = id
self._child_node = child_node
main.py
import mynode
def main():
n1 = MyNode('child1')
if __name__ == '__main__':
main()
但执行时发生以下错误。怎么解决这个问题?
...\py-tests>python main.py
Traceback (most recent call last):
File "main.py", line 1, in <module>
import mynode
File "...\py-tests\mynode.py", line 1, in <module>
class MyNode():
File "...\py-tests\mynode.py", line 2, in MyNode
def __init__(self, id: str=None, child_node: MyNode=None):
NameError: name 'MyNode' is not defined
答案 0 :(得分:2)
在定义__init__
时,类本身尚未定义,更不用说绑定到名称了。请改用forward reference,由字符串文字组成。
class MyNode:
def __init__(self, id: str = None, child_node: 'MyNode' = None):