我有一个简单的来源。
def h(x):
return x + 1
def m(x):
return x + 2
def n(x):
return x * 10
def function_aggregator(fun_list, num):
return_fun = None
for fun in fun_list[::-1]:
if return_fun:
return_fun = fun(return_fun)
else:
return_fun = fun(num)
return return_fun
if __name__ == "__main__":
lst = [h, m, n]
y = function_aggregator(lst, 4)
print(y)
有没有办法让function_aggregator
方法只接收列表并返回一个callable,它将与h(m(n(<any_number>))
答案 0 :(得分:0)
可以使用闭包来完成:
class A {
var s: String? = null //var accessed by multiple threads
set(s) {
synchronized(this) {
field = s
}
}
fun doStuff() {
synchronized(this) {
//safe now
}
}
}
def function_aggregator(*func_list):
def aggregate(num):
for func in reversed(func_list):
num = func(num)
return num
return aggregate
if __name__ == "__main__":
myfunc = function_aggregator(h, m, n)
print(myfunc(4))
现在需要任意数量的函数function_aggregator
,这是你正在讨论的 callable 。aggregate
将 callable ,AKA function_aggregator
返回给来电者aggregate
myfunc
视为一个函数,它接受一个参数并返回一些东西答案 1 :(得分:0)
之前的答案非常接近。确切的答案是:
def function_aggregator(fun_list):
def wrapper(arg):
for fun in reversed(fun_list):
arg = fun(arg)
return arg
return wrapper
if __name__ == "__main__":
lst = [g, f, n, m, h]
p = function_aggregator(lst)
x = 3
print("p(x): {}".format(p(x)))
感谢Zero Piraeus commet