foo()
未定义。你知道吗
>>> 0 and foo() (1)
0 # trivial
>>> 0 and foo() or 1 (2) # expecting it as 0 and (foo() or 1)
1 # does NOT short-circuit on 0
>>> 1 or foo() (3) # trivial
1
>>> 1 or foo() and 0 (4) # expecting it as 1 or (foo() and 0)
1 # DOES short-circuit on 1
从(2)和(4)中我看不到一致的行为。你知道吗
如果我们按照(2)的评估风格:
0 and foo() or 1
false or true (1)
true (1)
那么我期望(4)是:
1 or foo() and 0
true and false (0)
false (0)
如果我们按照(4)的评价方式:
1 or foo() and 0
true or ...
true (1)
那么我期望(2)是:
0 and foo() or 1
false and ...
false (0)
and
的优先级高于or
。你知道吗(2)
(4)
检查优先级:http://docs.python.org/reference/expressions.html#summary
它将在每一个情况下在
or
之前对and
进行评估。你知道吗1 or 2 and 3
==1 or (2 and 3)
你的问题来了,因为你相信
and
和or
仅仅是右联想,它们之间没有优先权。你知道吗and
在or
之前求值。你知道吗1 and 2 or 3
>;2
1 or 2 and 3
>;1
相关问题 更多 >
编程相关推荐