Python: 如何传递带有两个参数的函数作为实参
Python: How to pass function with two parameters as an argument
我有一个问题:
我需要在 python 中实现一个函数,它打印一个参数的标量倍数 - 参数本身就是一个具有签名的函数:
def innerF(a,b):
return x
标量乘数在函数中是一个常数 - 例如
return 55 * x
现在是我似乎没有得到的部分:
调用 Sytanx 必须是:
print( outerF(innerF)(a,b))
综上所述
def innerF(a,b):
return a + b
def outerF( #What goes here? ):
return 55* #How two call the innerF?
print(outerF(innerF)(a,b))
目前我所知道的:
我可以将 innerF 和 a,b 作为单独的参数传递给 outerF,例如
def outerF(innerF,a,b):
return 53* innerF(a,b)
我没有得到什么:
我完全不知道带有 innerF(outerF)(a,b)
的 outerF 调用的签名。我也找不到参考资料。
非常感谢您!
outerF
需要 return 一个用 (a, b)
调用的函数
def innerF(a, b):
return a + b
def outerF(func):
# define a function to return
def f(*args, **kwargs):
# this just calls the given func & scales it
return 55 * func(*args, **kwargs)
return f
print(outerF(innerF)(1, 2))
结果:
165 # 55 * (1+2)
所以你需要的是嵌套函数。
outerF(innerF)(a, b)
表示 outerF(innerF)
returns 一个新函数,然后将 a
和 b
作为参数。
要实现这一点,您需要一个 returns 函数。
def inner(a, b):
return a + b
def outer(func):
def wrapper(a, b):
return 55 * func(a, b)
return wrapper
outer(inner)(2, 3) # 275
您也可以将外部函数用作装饰器。
@outer
def inner(a, b):
return a + b
inner(2, 3) # 275
我有一个问题:
我需要在 python 中实现一个函数,它打印一个参数的标量倍数 - 参数本身就是一个具有签名的函数:
def innerF(a,b):
return x
标量乘数在函数中是一个常数 - 例如
return 55 * x
现在是我似乎没有得到的部分: 调用 Sytanx 必须是:
print( outerF(innerF)(a,b))
综上所述
def innerF(a,b):
return a + b
def outerF( #What goes here? ):
return 55* #How two call the innerF?
print(outerF(innerF)(a,b))
目前我所知道的:
我可以将 innerF 和 a,b 作为单独的参数传递给 outerF,例如
def outerF(innerF,a,b): return 53* innerF(a,b)
我没有得到什么:
我完全不知道带有 innerF(outerF)(a,b)
的 outerF 调用的签名。我也找不到参考资料。
非常感谢您!
outerF
需要 return 一个用 (a, b)
def innerF(a, b):
return a + b
def outerF(func):
# define a function to return
def f(*args, **kwargs):
# this just calls the given func & scales it
return 55 * func(*args, **kwargs)
return f
print(outerF(innerF)(1, 2))
结果:
165 # 55 * (1+2)
所以你需要的是嵌套函数。
outerF(innerF)(a, b)
表示 outerF(innerF)
returns 一个新函数,然后将 a
和 b
作为参数。
要实现这一点,您需要一个 returns 函数。
def inner(a, b):
return a + b
def outer(func):
def wrapper(a, b):
return 55 * func(a, b)
return wrapper
outer(inner)(2, 3) # 275
您也可以将外部函数用作装饰器。
@outer
def inner(a, b):
return a + b
inner(2, 3) # 275