繁体   English   中英

Python运算子优先

[英]Python operators precedence

我应该如何在Python中解释这句话(根据运算符的优先级)?

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

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

谢谢

使用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)

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

  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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM