python:AND执行的顺序

use*_*003 4 python boolean-logic

如果我有以下内容:

if a(my_var) and b(my_var):
    do something
Run Code Online (Sandbox Code Playgroud)

我可以假设,b()如果只计算a()True?或者它可能先做b()

问,因为评估b()时,会造成异常a()False.

Mar*_*ers 7

b()只有,a(my_var)是的True,才会被评估.and如果a(my_var)是假的话,操作员会短路.

布尔运算符文档:

表达式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
Run Code Online (Sandbox Code Playgroud)

Python将空容器和数字0值视为false:

>>> noisy(0) and noisy('whatever')
Called, returning 0
0
>>> noisy('') and noisy('whatever')
Called, returning ''
''
>>> noisy({}) and noisy('whatever')
Called, returning {}
{}
Run Code Online (Sandbox Code Playgroud)

自定义类可以实现一个__nonzero__钩子来为同一个测试返回一个布尔标志,或者如果它们是一个容器类型,则实现一个__len__钩子 ; 返回0意味着容器是空的并且被认为是假的.

在一个密切相关的说明中,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'
Run Code Online (Sandbox Code Playgroud)