以下两段代码是等效的吗?
if x is not None:
print("hello")
和:
if x is (not None):
print("hello")
不,没有等价物。is not
是一个运算符,根据 Python 的文档,我所知道的唯一一个带有空格的运算符:
运算符
is
并is 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