Python,如何将参数传递给函数指针参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13783211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python, how to pass an argument to a function pointer parameter?
提问by Byzantian
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 repeatinstead of foo?
在这种情况下,该函数foo("test")应该连续调用 4 次。有没有办法实现这一点,而不必通过“测试”来repeat代替foo?
采纳答案by Fred Foo
You can either use a lambda:
您可以使用lambda:
repeat(lambda: bar(42))
Or functools.partial:
或者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. *argsdenotes 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 *argsconstruct.
请注意,为方便起见,我将重复次数放在前面。如果要使用*args构造,它不能是最后一个参数。
(For completeness, you could add keyword arguments as well with **kwargs.)
(为了完整起见,您还可以使用**kwargs.添加关键字参数。)
回答by Hyperboreus
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)
回答by Peter Sichel
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):
return threading.Timer(seconds, method, params).start()
def cancelDelayedCall(timer):
timer.cancel()
# Example
def foo (a, b):
print ('{} are {}'.format (a, b) )
callMethodWithParametersAfterDelay(foo, ['roses', 'red'], 0)

