Python变量属性为None

时间:2014-10-17 02:21:23

标签: python tree

所以我有一个Tree类和节点类。 init是:

def __init__(self, key=None, left=None, right=None, p=None):
    self.key = key
    self.left = left
    self.right = right
    self.p = p

当我检查合适的孩子是否为无时,我会使用:

 print(x.right == None)

即使正确的孩子为无,这也总是返回False。

为了测试这个,我做了:

>>> print(x.right)
None
>>> print(x.right == None)
False

为什么会这样?

1 个答案:

答案 0 :(得分:0)

您是否可能意外地将right设置为字符串&#39;无&#39;,而不是 无< / strong>(没有引号)?

例如:

>>> x.right = 'None'  # Oops - accidentally used quotes
>>> print(x.right == None)
False
>>> print(x.right == 'None')
True

此外,最好使用is测试None,如:

>>> print(x.right is None)