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

标签 python

<分区>

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/48315777/

相关文章:

python - 使用 awk 或 perl 按键对文件进行排序,就像没有预排序的连接一样

python - 如何使用 WaterfallDialog 获取当前用户详细信息?

python - 如何只将具有最大值的行保留在同一类型项目的列中?

python - fit_transform() 需要 2 个位置参数,但 3 个是通过 LabelBinarizer 给出的

python - 运行时间太长

python - 全局变量无法传输值python

python - 尝试导入 scipy.stats 时出错 : No module named dual

python - Plotly choropleth_mapbox 的 GeoJSON 问题

python - 如何在 Python 中创建 PDF 文件

python - Keras 连接