Python:AND执行顺序

4
如果我有以下内容:
if a(my_var) and b(my_var):
    do something

我可以假设只有在 a()True 的情况下才会评估 b() 吗?或者它可能首先执行 b() 吗?
询问是因为当 a()False 时评估 b() 将导致异常。
4个回答

7
b()只有在a(my_var)为真时才会被执行,是的。如果a(my_var)是假值,那么and运算符将短路。从boolean operators documentation可以看到:

表达式x and y首先计算x;如果x为false,则返回其值;否则,计算y并返回结果值。

您可以使用一个调用时打印输出的函数进行测试:

>>> def noisy(retval):
...     print "Called, returning {!r}".format(retval)
...     return retval
... 
>>> noisy(True) and noisy('whatever')
Called, returning True
Called, returning 'whatever'
'whatever'
>>> noisy(False) and noisy('whatever')
Called, returning False
False

Python将空容器和数值0视为假:
>>> noisy(0) and noisy('whatever')
Called, returning 0
0
>>> noisy('') and noisy('whatever')
Called, returning ''
''
>>> noisy({}) and noisy('whatever')
Called, returning {}
{}

自定义类可以实现__nonzero__钩子来返回布尔标志进行相同的测试,或者如果它们是容器类型,则实现__len__钩子; 返回0表示容器为空且应视为false。

在一个紧密相关的注释中,or运算符执行相同的操作,但是反过来。如果第一个表达式评估为true,则不会评估第二个表达式:

>>> noisy('Non-empty string is true') or noisy('whatever')
Called, returning 'Non-empty string is true'
'Non-empty string is true'
>>> noisy('') or noisy('But an empty string is false')
Called, returning ''
Called, returning 'But an empty string is false'
'But an empty string is false'

1

help()的帮助下(哈哈):

>>> help('and')

Boolean operations
******************

   or_test  ::= and_test | or_test "or" and_test
   and_test ::= not_test | and_test "and" not_test
   not_test ::= comparison | "not" not_test

...

The expression ``x and y`` first evaluates *x*; if *x* is false, its
value is returned; otherwise, *y* is evaluated and the resulting value
is returned.

...

是的,如果a(my_var)返回False,则函数b将不会被调用。


1

是的,这样做是安全的。Python中的条件语句是惰性求值的。


0
编译器总是从上到下、从左到右读取。所以,如果编译器遇到 If False and True,它会首先遇到 False 并退出 if 条件。这对我所知道的所有软件都是有效的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接