如果我有以下内容:
if a(my_var) and b(my_var):
do something
我是否可以假设b()
仅在a()
为True
的情况下进行评估?或者它可能先b()
吗?
提问,因为评估b()
会在a()
为False
时导致异常。
答案 0 :(得分:7)
b()
为a(my_var)
时才会评估 True
,是的。如果and
为假,则a(my_var)
运算符会短路。
来自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值视为false:
>>> noisy(0) and noisy('whatever')
Called, returning 0
0
>>> noisy('') and noisy('whatever')
Called, returning ''
''
>>> noisy({}) and noisy('whatever')
Called, returning {}
{}
自定义类可以实现__nonzero__
hook以返回同一测试的布尔标志,或者如果它们是容器类型则实现__len__
hook;返回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 :(得分:1)
答案 2 :(得分: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
。
答案 3 :(得分:0)
编译器始终从上到下,从左到右读取。所以If False and True
然后编译器首先遇到False,它退出if条件。这适用于我所知道的所有软件。