我知道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
当你这么做的时候:
您错误地期望得到一个返回结果
test_a(x) and test_b(x)
的新函数。你实际上得到了evaluation of a Boolean expression:因为
test_a
和test_b
的truth value都是True
,所以condition
被设置为test_b
。这就是condition(menu)
给出与test_b(menu)
相同结果的原因。你知道吗要实现预期行为,请执行以下操作:
相关问题 更多 >
编程相关推荐