"x 不是 None"和"x is (not None)":它们是一样的吗?



以下两段代码是等效的吗?

if x is not None:
print("hello")

和:

if x is (not None):
print("hello")

不,没有等价物。is not是一个运算符,根据 Python 的文档,我所知道的唯一一个带有空格的运算符:

运算符isis not测试对象的标识:当且仅当 x 和 y 是同一对象时,x is y为真。对象的标识是使用id()函数确定的。x is not y产生反真值。

换句话说,这两个表达式是等效的,并且始终彼此相等:

(x is not None) == (not (x is None)) # always returns True

在第二个示例中,您没有使用is not运算符,而是分别使用is运算符和not运算符。not None的评估结果为True.因此我们可以得出结论,以下两个表达式是等价的,并且始终相等:

(x is (not None)) == (x is True) # always returns True

相关内容

最新更新