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)
?
我刚开始学习Python,发现我可以将一个函数作为另一个函数的参数传递。现在,如果我调用foo(bar()),它将不会作为函数指针传递,而是传递给函数的返回值。调用foo(bar)将传递函数,但这样我就无法传递任何其他参数。如果我想传递一个调用bar(42)的函数指针怎么办?
I want the ability to repeat a function regardless of what arguments I have passed to it.
无论我传递给它的参数是什么,我都希望能够重复一个函数。
def repeat(function, times):
for calls in range(times):
function()
def foo(s):
print s
repeat(foo("test"), 4)
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
?
在这种情况下,函数foo(“test”)应该被连续调用4次。有没有办法实现这一点,而不必通过“测试”来重复而不是foo?
3 个解决方案
#1
47
You can either use a lambda
:
你可以使用lambda:
repeat(lambda: bar(42))
Or functools.partial
:
from functools import partial
repeat(partial(bar, 42))
Or pass the arguments separately:
或者单独传递参数:
def repeat(times, f, *args):
for _ in range(times):
f(*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
这种最终样式在标准库和主要Python工具中非常常见。 * args表示可变数量的参数,因此您可以将此函数用作
repeat(4, foo, "test")
or
def inquisition(weapon1, weapon2, weapon3):
print("Our weapons are {}, {} and {}".format(weapon1, weapon2, weapon3))
repeat(10, inquisition, "surprise", "fear", "ruthless efficiency")
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.
请注意,为方便起见,我将重复次数放在前面。如果要使用* args构造,它不能是最后一个参数。
(For completeness, you could add keyword arguments as well with **kwargs
.)
(为了完整起见,您可以添加关键字参数以及** kwargs。)
#2
14
You will need to pass the parameters for foo, to the repeat function:
您需要将foo的参数传递给repeat函数:
#! /usr/bin/python3.2
def repeat (function, params, times):
for calls in range (times):
function (*params)
def foo (a, b):
print ('{} are {}'.format (a, b) )
repeat (foo, ['roses', 'red'], 4)
repeat (foo, ['violets', 'blue'], 4)
#3
1
While many of the answers here are good, this one might be helpful because it doesn't introduce any unnecessary repetition and the reason for callbacks in the first place is often to synchronize with other work outside of the main UI thread.
虽然这里的许多答案都很好,但这个答案可能会有所帮助,因为它不会引入任何不必要的重复,并且首先回调的原因通常是与主UI线程之外的其他工作同步。
Enjoy!
import time, threading
导入时间,线程
def callMethodWithParamsAfterDelay(method=None, params=[], seconds=0.0):
def callMethodWithParamsAfterDelay(method = None,params = [],seconds = 0.0):
return threading.Timer(seconds, method, params).start()
def cancelDelayedCall(timer):
timer.cancel()
Example
def foo (a, b):
def foo(a,b):
print ('{} are {}'.format (a, b) )
callMethodWithParametersAfterDelay(foo, ['roses', 'red'], 0)
callMethodWithParametersAfterDelay(foo,['roses','red'],0)
#1
47
You can either use a lambda
:
你可以使用lambda:
repeat(lambda: bar(42))
Or functools.partial
:
from functools import partial
repeat(partial(bar, 42))
Or pass the arguments separately:
或者单独传递参数:
def repeat(times, f, *args):
for _ in range(times):
f(*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
这种最终样式在标准库和主要Python工具中非常常见。 * args表示可变数量的参数,因此您可以将此函数用作
repeat(4, foo, "test")
or
def inquisition(weapon1, weapon2, weapon3):
print("Our weapons are {}, {} and {}".format(weapon1, weapon2, weapon3))
repeat(10, inquisition, "surprise", "fear", "ruthless efficiency")
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.
请注意,为方便起见,我将重复次数放在前面。如果要使用* args构造,它不能是最后一个参数。
(For completeness, you could add keyword arguments as well with **kwargs
.)
(为了完整起见,您可以添加关键字参数以及** kwargs。)
#2
14
You will need to pass the parameters for foo, to the repeat function:
您需要将foo的参数传递给repeat函数:
#! /usr/bin/python3.2
def repeat (function, params, times):
for calls in range (times):
function (*params)
def foo (a, b):
print ('{} are {}'.format (a, b) )
repeat (foo, ['roses', 'red'], 4)
repeat (foo, ['violets', 'blue'], 4)
#3
1
While many of the answers here are good, this one might be helpful because it doesn't introduce any unnecessary repetition and the reason for callbacks in the first place is often to synchronize with other work outside of the main UI thread.
虽然这里的许多答案都很好,但这个答案可能会有所帮助,因为它不会引入任何不必要的重复,并且首先回调的原因通常是与主UI线程之外的其他工作同步。
Enjoy!
import time, threading
导入时间,线程
def callMethodWithParamsAfterDelay(method=None, params=[], seconds=0.0):
def callMethodWithParamsAfterDelay(method = None,params = [],seconds = 0.0):
return threading.Timer(seconds, method, params).start()
def cancelDelayedCall(timer):
timer.cancel()
Example
def foo (a, b):
def foo(a,b):
print ('{} are {}'.format (a, b) )
callMethodWithParametersAfterDelay(foo, ['roses', 'red'], 0)
callMethodWithParametersAfterDelay(foo,['roses','red'],0)