如何将参数传递给函数指针参数?
- 2025-03-20 08:48:00
- admin 原创
- 41
问题描述:
我刚开始学习 Python,发现我可以将一个函数作为另一个函数的参数传递。现在如果我调用,foo(bar())
它将不会作为函数指针传递,而是作为所用函数的返回值传递。调用foo(bar)
将传递函数,但这样我就无法传递任何其他参数。如果我想传递一个调用的函数指针怎么办bar(42)
?
我希望能够重复一个函数,无论我传递给它什么参数。
def repeat(function, times):
for calls in range(times):
function()
def foo(s):
print s
repeat(foo("test"), 4)
在这种情况下,该函数foo("test")
应该连续调用 4 次。有没有办法实现这一点,而不必将“test”传递给repeat
而不是foo
?
解决方案 1:
您可以使用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")
或者
def inquisition(weapon1, weapon2, weapon3):
print("Our weapons are {}, {} and {}".format(weapon1, weapon2, weapon3))
repeat(10, inquisition, "surprise", "fear", "ruthless efficiency")
请注意,为了方便起见,我将重复次数放在前面。如果您想使用该*args
构造,它不能是最后一个参数。
(为了完整性,您也可以使用 添加关键字参数**kwargs
。)
解决方案 2:
您需要将 foo 的参数传递给重复函数:
#! /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:
虽然这里的许多答案都很好,但这个答案可能会有所帮助,因为它不会引入任何不必要的重复,并且回调的原因通常是为了与主 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)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD