问题
How should I interpret this sentence in Python (in terms of operators precedence)?
c = not a == 7 and b == 7
as c = not (a == 7 and b == 7)
or c = (not a) == 7 and b == 7
?
thanks
回答1:
Using dis
module:
>>> 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
So, it looks like:
c = (not(a == 7)) and (b == 7)
回答2:
According to the documentation the order is, from lowest precedence (least binding) to highest precedence (most binding):
and
not
==
So the expression not a == 7 and b == 7
will be evaluated like this:
((not (a == 7)) and (b == 7))
^ ^ ^ ^
second first third first
In other words, the evaluation tree will look like this:
and
/ \
not ==
| / \
== b 7
/ \
a 7
And the last thing done will be the assignment of the expression's value to c
.
来源:https://stackoverflow.com/questions/19009898/python-operators-precedence