Python,如何将参数传递给函数指针参数?
我刚刚开始学习Python,发现我可以将一个函数作为另一个函数的参数传递。现在,如果我调用Python,如何将参数传递给函数指针参数?,python,callback,function-pointers,Python,Callback,Function Pointers,我刚刚开始学习Python,发现我可以将一个函数作为另一个函数的参数传递。现在,如果我调用foo(bar()),它将不会作为函数指针传递,而是所用函数的返回值。调用foo(bar)将传递函数,但这样我就无法传递任何附加参数。如果我想传递一个调用条(42)的函数指针,该怎么办 我希望能够重复一个函数,而不管我传递给它的参数是什么 def repeat(function, times): for calls in range(times): function() def f
foo(bar())
,它将不会作为函数指针传递,而是所用函数的返回值。调用foo(bar)
将传递函数,但这样我就无法传递任何附加参数。如果我想传递一个调用条(42)
的函数指针,该怎么办
我希望能够重复一个函数,而不管我传递给它的参数是什么
def repeat(function, times):
for calls in range(times):
function()
def foo(s):
print s
repeat(foo("test"), 4)
在这种情况下,函数foo(“test”)
应连续调用4次。
有没有一种方法可以做到这一点,而不必通过对
repeat
而不是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
表示可变数量的参数,因此您可以将此函数用作
repeat(4, foo, "test")
或
请注意,为了方便起见,我将重复次数放在前面。如果要使用*args
构造,它不能是最后一个参数
(为了完整性,您还可以使用
**kwargs
添加关键字参数)您需要将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)
虽然这里的许多答案都是好的,但这一个可能会有所帮助,因为它不会引入任何不必要的重复,而且回调的首要原因通常是与主UI线程之外的其他工作同步 享受吧
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)
旁注:这些不是“函数指针”!在Python中,函数是对象。
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)