gpt4 book ai didi

python - "a is a is a"比较结果

转载 作者:太空宇宙 更新时间:2023-11-03 21:24:12 25 4
gpt4 key购买 nike

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"

关于python - "a is a is a"比较结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53970384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com