【问题标题】:How to declare types for uninitialized variables in Python? [duplicate]如何在 Python 中声明未初始化变量的类型? [复制]
【发布时间】:2023-04-09 03:48:01
【问题描述】:

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

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

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】:

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

    【讨论】:

    • 啊,谢谢。两种选择都是合理的还是一种比另一种更标准?
    • @user2415706 没问题。这两个选项绝对是合理的,但在这种情况下,我认为Optional 是一个更好的选择,因为它特别暗示Node 的孩子可能存在也可能不存在,并且它引入了更好的类型安全性,因为现在你必须在能够使用它的值之前检查孩子is not None 是否。我还认为检查变量是否为None 看起来比检查它是否具有某种类型更干净
    猜你喜欢
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多