Python函数短路

2024-04-23 22:24:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道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

Tags: andintest功能falsereturndefstdin
1条回答
网友
1楼 · 发布于 2024-04-23 22:24:44

当你这么做的时候:

>>> condition = test_a and test_b

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

x and y: if x is false, then x, else y

因为test_atest_btruth value都是True,所以condition被设置为test_b。这就是condition(menu)给出与test_b(menu)相同结果的原因。你知道吗

要实现预期行为,请执行以下操作:

>>> def condition(x):
...     return test_a(x) and test_b(x)
...

相关问题 更多 >