Python,如何将参数传递给函数指针参数?

Byz*_*ian 41 python function-pointers callback

我刚开始学习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)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,该函数foo("test")应该连续调用4次.有没有办法实现这一点,而不必通过"测试" repeat代替foo

Fre*_*Foo 63

你可以使用lambda:

repeat(lambda: bar(42))
Run Code Online (Sandbox Code Playgroud)

或者functools.partial:

from functools import partial
repeat(partial(bar, 42))
Run Code Online (Sandbox Code Playgroud)

或者单独传递参数:

def repeat(times, f, *args):
    for _ in range(times):
        f(*args)
Run Code Online (Sandbox Code Playgroud)

这种最终样式在标准库和主要Python工具中非常常见.*args表示可变数量的参数,因此您可以将此函数用作

repeat(4, foo, "test")
Run Code Online (Sandbox Code Playgroud)

要么

def inquisition(weapon1, weapon2, weapon3):
    print("Our weapons are {}, {} and {}".format(weapon1, weapon2, weapon3))

repeat(10, inquisition, "surprise", "fear", "ruthless efficiency")
Run Code Online (Sandbox Code Playgroud)

请注意,为方便起见,我将重复次数放在前面.如果要使用该*args构造,它不能是最后一个参数.

(为完整起见,您也可以添加关键字参数**kwargs.)


Hyp*_*eus 17

您需要将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)
Run Code Online (Sandbox Code Playgroud)