我应该如何在Python中解释这句话(根据运算符优先级)?
c = not a == 7 and b == 7
为c = not (a == 7 and b == 7)
或c = (not a) == 7 and b == 7
?
感谢
答案 0 :(得分: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)
答案 1 :(得分:2)
根据documentation顺序,从最低优先级(最少绑定)到最高优先级(最多绑定):
and
not
==
因此表达式not a == 7 and b == 7
将按如下方式进行评估:
((not (a == 7)) and (b == 7))
^ ^ ^ ^
second first third first
换句话说,评估树将如下所示:
and
/ \
not ==
| / \
== b 7
/ \
a 7
最后一件事就是将表达式的值赋值给c
。