我应该如何解释Python中的这句话(根据运算符优先级)?Python运算符优先级
c = not a == 7 and b == 7
为c = not (a == 7 and b == 7)
或c = (not a) == 7 and b == 7
?
感谢
我应该如何解释Python中的这句话(根据运算符优先级)?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)
按照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
。
您给出的链接表示该列表按最低优先级排序,因此它会是'(not(a == 7))和(b == 7)''。如果它是从最高到最低,就像你说的那样,那么它将是'((不是a)==(7和b))== 7',因为'和'会比'=='更高的优先级。 –
@EricFinn是的,我的错误 - 修好了! –
http://docs.python.org/2/reference/expressions.html#operator-precedence – George