如何在 Python 中声明未初始化变量的类型?

How to declare types for uninitialized variables in Python?

我正在学习使用 mypy 和静态类型检查器,同时练习算法和数据结构。

在二叉搜索树中,节点初始化时没有子节点。它们是节点类型。但是,似乎 None 是 Python 中它自己的对象类型,所以 mypy 在下面给我一个错误。是否可以将未分配的子项初始化为 Node 类型?

binary_search_tree.py:17: error: Incompatible types in assignment (expression has type "None", variable has type "Node")
binary_search_tree.py:18: error: Incompatible types in assignment (expression has type "None", variable has type "Node")
Found 2 errors in 1 file (checked 1 source file)

代码如下:

class Node:
    # A node has a value which is an int and two children which are nodes
    def __init__(self, value: int):
        self.value: int = value
        self.left: Node = None
        self.right: Node = None 

因为这些值有时可以是 None,所以您应该将它们指定为 Optional 类型,然后在使用它们时执行明确的 None 检查,以便 mypy就会知道它们具有价值。更多信息来自 mypy 的文档 here:

from typing import Optional

class Node:
    # A node has a value which is an int and two children which are nodes
    def __init__(self, value: int):
        self.value: int = value
        self.left: Optional[Node] = None
        self.right: Optional[Node] = None

如果将它们初始化为 None,则不可能将它们声明为仅 Node 类型。另一种选择是创建一个 NullNode (或类似的东西)子类,它仍然具有类型 Node 但表示那里没有 Node

class Node:
    # A node has a value which is an int and two children which are nodes
    def __init__(self, value: int):
        self.value: int = value
        self.left: Node = NullNode()
        self.right: Node = NullNode()

class NullNode(Node):
    pass