Python,如何传递参数到函数指针参数? [英] Python, how to pass an argument to a function pointer parameter?
问题描述
我刚刚开始学习Python,发现我可以传递一个函数作为另一个函数的参数。现在如果我调用 foo(bar())
它不会作为一个函数指针,但使用的函数的返回值。调用 foo(bar)
将传递函数,但是这种方式我不能传递任何额外的参数。如果我想传递一个函数指针调用 bar(42)
?
I only just started learning Python and found out that I can pass a function as the parameter of another function. Now if I call foo(bar())
it will not pass as a function pointer but the return value of the used function. Calling foo(bar)
will pass the function, but this way I am not able to pass any additional arguments. What if I want to pass a function pointer that calls bar(42)
?
def repeat(function, times):
for calls in range(times):
function()
def foo(s):
print s
repeat(foo("test"), 4)
在这种情况下,函数 foo(test)
应该连续调用4次。有没有办法实现这一点,而不必传递测试到
重复
而不是 foo
?
In this case the function foo("test")
is supposed to be called 4 times in a row.
Is there a way to accomplish this without having to pass "test" to repeat
instead of foo
?
推荐答案
您可以使用 lambda
:
repeat(lambda: bar(42))
或 functools.partial
:
from functools import partial
repeat(partial(bar, 42))
:
def repeat(times, f, *args):
for _ in range(times):
f(*args)
这种最终样式在标准库和主要的Python工具中很常见。 * args
表示可变数量的参数,因此您可以将此函数用作
This final style is quite common in the standard library and major Python tools. *args
denotes a variable number of arguments, so you can use this function as
repeat(4, foo, "test")
或
def inquisition(weapon1, weapon2, weapon3):
print("Our weapons are {}, {} and {}".format(weapon1, weapon2, weapon3))
repeat(10, inquisition, "surprise", "fear", "ruthless efficiency")
请注意,为方便起见,我将重复次数放在前面。如果要使用 * args
构造,它不能是最后一个参数。
Note that I put the number of repetitions up front for convenience. It can't be the last argument if you want to use the *args
construct.
您可以添加关键字参数以及 ** kwargs
。)
(For completeness, you could add keyword arguments as well with **kwargs
.)
这篇关于Python,如何传递参数到函数指针参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!