Python中,如何将参数传递给一个函数指针参数?(Python, how to pass an a

2019-07-04 19:37发布

我才刚刚开始学习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倍。 有没有办法做到这一点,而不必通过“测试”,以repeat的,而不是foo

Answer 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 )。



Answer 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)


Answer 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)


文章来源: Python, how to pass an argument to a function pointer parameter?