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)
答案 0 :(得分:5)
and
的优先级高于or
。
0 and foo() or 1 == (0 and foo()) or 1
== 0 or 1 # short-circuited, foo() never evaluated
== 1
1 or foo() and 0 == 1 or (foo() and 0)
== 1 # short-circuited, foo() never evaluated
答案 1 :(得分:2)
检查优先级:http://docs.python.org/reference/expressions.html#summary
它会在每个案例and
之前评估or
。
1 or 2 and 3
== 1 or (2 and 3)
答案 2 :(得分:1)
您遇到问题是因为您认为and
和or
仅仅是正确关联的,并且它们之间没有优先权。
and
之前评估 or
。
1 and 2 or 3
- > 2
1 or 2 and 3
- > 1
>>> def foo():
... print 'foo'
... return 0
...
>>> def bar():
... print 'bar'
... return 1
...
>>> def baz():
... print 'baz'
... return 2
...
>>> foo() and bar() or baz()
foo
baz
2