如何使用相同类型的成员创建静态类型的python类

时间:2018-05-29 16:11:19

标签: python python-3.x mypy

我来自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

1 个答案:

答案 0 :(得分:2)

在定义__init__时,类本身尚未定义,更不用说绑定到名称了。请改用forward reference,由字符串文字组成。

class MyNode:
    def __init__(self, id: str = None, child_node: 'MyNode' = None):