Skip to main content
 首页 » 编程设计

python之如何将嵌套函数作为参数传递

2025年05月04日13findumars

假设我们在 python 中有函数:

def _abs(iterable):   #cause its normally for one element only 
    return [abs(i) for i in iterable] 
 
def A(list, foo): 
    return foo(list) 
 
list = [2,3,-5] 
print( A(list,foo=sum) ) 
 
>> 0 

虽然我可能会将 foo=sum 传递给 A,但我正在寻找一种优雅的方式来传递类似 foo=sum(_abs) 的东西来执行 sum (_abs(列表))。

我现在看到的唯一方法是发送函数列表 [sum, _abs] 并按顺序应用它们。有没有更好的办法?

请您参考如下方法:

或者,更一般地组合(即使用任意数量的参数函数):

from functools import partial, reduce 
 
def compose(*funcs): 
    return partial(reduce, lambda x, f: f(x), reversed(funcs)) 

(请参阅 partial 和 reduce 上的文档 - 注意您不需要在 Python 2.x 中导入 reduce)

然后:

>>> compose(sum, _abs)([2, 3, -5]) 
10