【问题标题】:How to pass an argument to a function pointer parameter?如何将参数传递给函数指针参数?
【发布时间】:2012-11-26 19:39:44
【问题描述】:

我刚开始学习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

【问题讨论】:

标签: python callback function-pointers


【解决方案1】:

虽然这里的许多答案都很好,但这个答案可能会有所帮助,因为它不会引入任何不必要的重复,而且首先回调的原因通常是与主 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)

【讨论】:

    【解决方案2】:

    您可以使用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 添加关键字参数。)

    【讨论】:

      【解决方案3】:

      您需要将 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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-07
        • 1970-01-01
        • 1970-01-01
        • 2021-07-18
        • 1970-01-01
        • 2018-08-25
        • 2019-08-17
        相关资源
        最近更新 更多