“a是a是a”比较的结果

2024-10-03 17:15:07 发布

您现在位置: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.')

结果:

^{pr2}$

我知道在if语句中使用两个“=”s和“is”是不正常的。但是我想知道Python解释器是如何设置if语句的。在

表达式lie is lie is lie是同时解释的还是短路的?在


Tags: ofnotrueifis语句howsmall
3条回答

它将被解释为:

lie = 0
if lie is lie and lie is lie:
    ...

这个问题已经有很多答案,但是请考虑将函数拆分为字节码:

def f():
    lie = 0
    if lie is lie is lie:
        print('Lie')

dis.dis(f)

  2           0 LOAD_CONST               1 (0)
              2 STORE_FAST               0 (lie)
  3           4 LOAD_FAST                0 (lie)
              6 LOAD_FAST                0 (lie)
              8 DUP_TOP
             10 ROT_THREE
             12 COMPARE_OP               8 (is)
             14 JUMP_IF_FALSE_OR_POP    22
             16 LOAD_FAST                0 (lie)
             18 COMPARE_OP               8 (is)
             20 JUMP_FORWARD             4 (to 26)
        >>   22 ROT_TWO
             24 POP_TOP
        >>   26 POP_JUMP_IF_FALSE       36
  4          28 LOAD_GLOBAL              0 (print)
             30 LOAD_CONST               2 ('Lie')
             32 CALL_FUNCTION            1
             34 POP_TOP
        >>   36 LOAD_CONST               0 (None)
             38 RETURN_VALUE

这表明所有lie都在以线性方式检查它们是否匹配。如果一个失败了,它应该会断开/返回。在

要确认,请考虑:

^{pr2}$

你所遇到的叫做操作符链。在

来自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"

相关问题 更多 >