多个和/或表达式

时间:2011-07-04 23:26:24

标签: python

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)的一致行为。

案例1

如果按照(2)的评估方式进行评估:

0 and foo() or 1
false or true (1)
true (1)

然后我希望(4)为:

1 or foo() and 0
true and false (0)
false (0)

案例2

如果按照(4)的评估方式进行评估:

1 or foo() and 0
true or ...
true (1)

然后我希望(2)为:

0 and foo() or 1
false and ...
false (0)

3 个答案:

答案 0 :(得分:5)

and的优先级高于or

(2)

0 and foo() or 1 == (0 and foo()) or 1
                 == 0 or 1  # short-circuited, foo() never evaluated
                 == 1

(4)

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)

您遇到问题是因为您认为andor仅仅是正确关联的,并且它们之间没有优先权。

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