在Python中,可以将函数作为一个参数传递给另外一个函数,具体用法如下:
def add(a,b):
return a+b
def multip(a,b):
return a*b
def apply_func(func,a,b):
return func(a,b)
result1 = apply_func(add,2,5)
print('The result1 is :',result1)
>>>The result1 is : 7
result2 = apply_func(multip,2,5)
print('The result2 is :',result2)
>>>The result1 is : 10
首先定义了两个数加法和两个数乘法的函数,再定义了一个apply_func函数来接收上面函数作为参数。其中apply_func是将接受到的函数进行调用的结果作为返回值。
此外,还可以将多个函数作为参数传进函数进行操作:
def add(a,b):
return a+b
def multip(a,b):
return a*b
def apply_func(func,a,b):
return func(a,b)
def apply_funcs(func1,func2,*args):
a,b=args
return func1(a,b)*func2(a,b)
result2 = apply_funcs(add,multip,2,5)
print('The result2 is :',result2)
>>>The result2 is : 70
在这个示例中我们同时将两个函数作为参数传入了apply_funcs函数中,并将这两个函数的结果再相乘作为返回值。
稍作拓展,这里*args的用法是关于“打包与解包”的语法,有兴趣的朋友可以看我的另外一篇博客: