为什么Python会以这种方式进行评估:
>>> False is False is False
True
但是当用括号尝试时,它的表现与预期相符:
>>> (False is False) is False
False
为什么Python会以这种方式进行评估:
>>> False is False is False
True
但是当用括号尝试时,它的表现与预期相符:
>>> (False is False) is False
False
a is b is c
相当于 a is b and b is c
。False is False and False is False
,它会被计算为 True and True
然后计算为 True
。(a is b) is c
会将 a is b
的结果与 c
进行比较。a
、b
、c
、...、y
、z
是表达式,而 op1
、op2
、...、opN
是比较运算符,则 a op1 b op2 c ... y opN z
等价于 a op1 b and b op2 c and ... y opN z
,除了每个表达式最多只计算一次。False is False is False
的计算结果为(False is False) and (False is False)
False is False
表达式使用了原始表达式中的第二个False
,这实际上相当于True and True
True
。但在第二个表达式中,求值顺序如下。(False is False) is False
实际上是
True is False
这就是为什么结果是False
。
False is False is False
被视为
(False is False) and (False is False)
所以你得到了
True and True
并且会评估为True
。
您也可以将此类型的链接与其他运算符一起使用。
1 < x < 10
0 > 2 is False
返回 False
-> 多么直观的行为 :) - pbaranski(0 > 2)
是 False。 - cs95False is False is False
"的意思是 "(False is False) and (False is False)
", 但"(False is False) is False
"的意思是:>>> (False is False) is False
False
>>> a_true = (False is False)
>>> a_true
True
>>> a_true is False
False
>>> False is False is False
True
False
对都会被评估。前两个 False 被评估,如果它是 True
,那么第二个和第三个 False
将被评估并返回结果。False is False is False
等同于 2 条命令 False is False
的结果的 and
。
eval(" is ".join(["False" for i in range(n)]))
- Daniel Levin1 < 2 < 3 < 4
,因此可以表示为:1<2 and 2<3 and 3<4
。 - pbaranskiNone is None is None
。 - Blacklight Shining