python - 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