我定义了一个带有类型注释的TreeNode类。它为__init__
和某些类方法中的参数接受TreeNode或None。完整的代码在测试过程中运行良好,但是当我用mypy检查时,它会列出4条警告。我正在使用Python 3.7.4和mypy版本0.74。
我尝试使用Optional [“ TreeNode”]和Union [“ TreeNode”,None]关键字进行尝试,但是错误仍然存在。请注意,TreeNode周围的引号是必需的,因为它是在完全定义类型之前对类型的前向引用。
from typing import * class TreeNode(): def __init__(self, value, parent : Optional["TreeNode"]=None, left_child : Optional["TreeNode"]=None, right_child : Optional["TreeNode"]=None): self.value = value self.parent = parent self.left_child = None self.right_child = None self.update_children(left_child, right_child) def get_parent(self): return self.parent def set_parent(self, other): self.parent = other def update_children(self, left_child : Optional["TreeNode"] = None, right_child : Optional["TreeNode"] = None): # update parents in children, if left or right not None. if left_child: self.left_child = left_child self.left_child.set_parent(self) if right_child: self.right_child = right_child self.right_child.set_parent(self) def depth(self): pass # full code omitted for brevity
这是mypy的输出:
tree_node.py:25: error: Incompatible types in assignment (expression has type "TreeNode", variable has type "None") tree_node.py:26: error: "None" has no attribute "set_parent" tree_node.py:28: error: Incompatible types in assignment (expression has type "TreeNode", variable has type "None") tree_node.py:29: error: "None" has no attribute "set_parent"
我还尝试了对mypy抱怨的代码进行以下修改,但无济于事:
if left_child is not None: self.left_child = left_child self.left_child.set_parent(self) if right_child is not None: self.right_child = right_child self.right_child.set_parent(self)
问题是当我明确指出TreeNode或None都可以,并且仅在不为None的情况下才执行有问题的代码时,为什么会出现这些错误?
我定义了一个带有类型注释的TreeNode类。它接受__init__和某些类方法中的参数的TreeNode或None。完整的代码在测试过程中运行良好,但是当我...
问题与您在构造函数中设置左右子项的方式有关,特别是这两行: