A = 314
if A == A == A:
print('True #1')
if A == A == 271:
print('True #2')
lie = 0
if lie is lie is lie:
print('no matter how white, how small,')
print('how incorporating of a smidgeon')
print('of truth there be in it.')
结果:
True #1
no matter how white, how small,
how incorporating of a smidgeon
of truth there be in it.
我知道在 if 语句中使用两个“=”和“is”是不正常的。但我想知道 Python 解释器如何解释 if
语句。
表达式lie is lie is lie
是同时解释的,还是短路的方式?
您遇到的情况称为运算符链接。
来自 Comparisons 上的文档:
Comparisons can be chained arbitrarily, e.g., x < y <= z
is
equivalent to x < y and y <= z
, except that y
is evaluated only once
(but in both cases z
is not evaluated at all when x < y
is found to be
false).
强调我的。
所以,这意味着 lie is lie is lie
被解释为 (lie is lie) and (lie is lie)
,仅此而已。
更一般地说,a op b op c op d ...
被评估为与 a op b and b op c and c op d ...
相同等等。表达式根据python的grammar rules解析.特别是;
comparison ::= or_expr ( comp_operator or_expr )*
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="
| "is" ["not"] | ["not"] "in"