Python Forward References

Python3中加入了对 Type 的支持,但是在下面的例子中:

1
2
3
4
class Node:

    def __init__(self, val: int, left_child: Node=None, right_child: Node=None):
        pass

Python会抱怨Node is not defined..出现这种情况的原因是,我们在Node的定义还没有完全结束的时候引用了它。解决的方法是使用string来标注这个type:

1
2
3
4
class Node:

    def __init__(self, val: int, left_child: 'Node'=None, right_child: 'Node'=None):
        pass

这种方法叫做 Forward References.