Python短路功能

问题描述 投票:0回答:1

我知道Python的短路行为适用于函数。当两个函数合并为一个时,有什么理由不起作用吗?即,为什么这个短路,

>>> menu = ['spam']
>>> def test_a(x):
...     return x[0] == 'eggs'  # False.
...
>>> def test_b(x):
...     return x[1] == 'eggs'  # Raises IndexError.
...
>>> test_a(menu) and test_b(menu)
False

这不是吗?

>>> condition = test_a and test_b
>>> condition(menu)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in test_b
IndexError: list index out of range
python short-circuiting
1个回答
1
投票

当你这样做:

>>> condition = test_a and test_b

你错误地期望得到一个返回结果test_a(x) and test_b(x)的新函数。你实际上得到了evaluation of a Boolean expression

x and y:如果x为假,则为x,否则为y

由于truth valuetest_atest_bTruecondition被设置为test_b。这就是为什么condition(menu)给出与test_b(menu)相同的结果。

要实现预期的行为,请执行:

>>> def condition(x):
...     return test_a(x) and test_b(x)
...
© www.soinside.com 2019 - 2024. All rights reserved.