def basket(name, colour, smell, rotten=None):
if rotten:
if rotten():
return "Can't eat!"
return ("The fruit, {}, is {} in colour"
"and smells like {}.".format(name, colour, smell))
在上面的示例代码中,如果提供了参数 rotten
,则会在调用之前进行检查。它必须是一个返回 bool 值的函数(为了简单起见,没有参数)。它消耗了两行代码,我不确定这是否是该过程的常规样式。我想到的另一种方法是将当前的替换为:
def basket(name, colour, smell, rotten=lambda: None):
if rotten(): # Saved a line here
return "Can't eat!"
return ("The fruit, {}, is {} in colour"
" and smells {}.".format(name, colour, smell))
lambda方法节省一行;除此之外我不知道哪一个比另一个有优势。这样做的最佳方法是什么?在标准库代码中的任何地方都可以找到它吗?
最佳答案
您可以像第一个示例一样保留函数签名不变,并利用boolean operations's short circuit behavior将其变成这样的一行:
def basket(name, colour, smell, rotten=None):
if rotten and rotten():
return "Can't eat!"
return ("The fruit, {}, is {} in colour"
"and smells like {}.".format(name, colour, smell))
如果rotten
为None
,则and
表达式将因短路而失败,而不会调用rotten()
。如果 rotten
不是 None
,它将继续调用 rotten()
并在谓词为 True
时成功。
注意:正如评论中提到的,您还可以使用函数 callable()
并在实际调用之前检查是否可以调用 rotten
:
if callable(rotten) and rotten():
当 rotten
不是 None
但不是可调用对象时(传递 rotten=True
for例子)。否则,如果您希望该函数在传递不可调用函数时大声提示,那么就让它保持原样。
关于python - 将函数作为命名参数传递以进行条件检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23018692/