1

我应该如何在 Python 中解释这句话(就运算符优先级而言)?

c = not a == 7 and b == 7

作为c = not (a == 7 and b == 7)c = (not a) == 7 and b == 7

谢谢

4

2 回答 2

5

使用dis模块:

>>> import dis
>>> def func():
...     c = not a == 7 and b == 7
...     
>>> dis.dis(func)
  2           0 LOAD_GLOBAL              0 (a)
              3 LOAD_CONST               1 (7)
              6 COMPARE_OP               2 (==)
              9 UNARY_NOT           
             10 JUMP_IF_FALSE_OR_POP    22
             13 LOAD_GLOBAL              1 (b)
             16 LOAD_CONST               1 (7)
             19 COMPARE_OP               2 (==)
        >>   22 STORE_FAST               0 (c)
             25 LOAD_CONST               0 (None)
             28 RETURN_VALUE  

所以,它看起来像:

c = (not(a == 7)) and (b == 7)
于 2013-09-25T16:09:13.377 回答
2

根据文档,顺序是从最低优先级(最少绑定)到最高优先级(最多绑定):

  1. and
  2. not
  3. ==

所以表达式not a == 7 and b == 7将被计算如下:

((not (a == 7)) and (b == 7))
   ^     ^       ^     ^
second first   third first

换句话说,评估树将如下所示:

      and
     /   \
   not   ==
    |   /  \
   ==   b  7
  /  \
  a  7

最后完成的事情是将表达式的值分配给c.

于 2013-09-25T16:09:50.070 回答