首页 > 解决方案 > 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

标签: pythonshort-circuiting

解决方案


当你这样做时:

>>> condition = test_a and test_b

你错误地期望得到一个返回结果的新函数test_a(x) and test_b(x)。您实际上得到了布尔表达式的评估

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

由于两者的真值test_atest_bTruecondition被设置为test_b。这就是为什么condition(menu)给出与 相同的结果test_b(menu)

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

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

推荐阅读