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

问题描述 投票:0回答:1

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

在二叉搜索树中,没有任何子节点的节点被初始化。它们是节点类型。但是,似乎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 
python python-3.x types mypy dynamic-typing
1个回答
2
投票

因为这些值有时可以是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

否则,如果将它们初始化为Node,就不可能仅将它们声明为None类型。另一个选择是创建一个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
© www.soinside.com 2019 - 2024. All rights reserved.