Python函数短路

Python函数短路,python,short-circuiting,Python,Short Circuiting,我知道Python的短路行为与函数一起工作。当两个函数合并成一个函数时,有什么理由它不起作用吗?也就是说,为什么会发生短路 >>> menu = ['spam'] >>> def test_a(x): ... return x[0] == 'eggs' # False. ... >>> def test_b(x): ... return x[1] == 'eggs' # Raises IndexError. ... >

我知道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
>>条件=测试a和测试b
>>>条件(菜单)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第2行,在测试_b中
索引器:列表索引超出范围
执行此操作时:

>>> condition = test_a and test_b
您错误地期望得到一个返回结果的新函数
test_a(x)和test_b(x)
。你实际上得到了:

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

由于
test_a
test_b
的值均为
True
条件设置为
test_b
。这就是为什么
条件(菜单)
给出与
测试(菜单)
相同的结果

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

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