我在练习算法和数据结构的同时学习使用 mypy 和静态类型检查器。
在二叉搜索树中,节点初始化时没有子节点。它们属于 Node.js 类型。但是,在 Python 中似乎 None 是它自己的对象类型,所以 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
文档的更多信息:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句