Python, how to pass an argument to a function pointer parameter?

核能气质少年 提交于 2019-11-29 00:56:41

You can either use a lambda:

repeat(lambda: bar(42))

Or functools.partial:

from functools import partial
repeat(partial(bar, 42))

Or pass the arguments separately:

def repeat(times, f, *args):
    for _ in range(times):
        f(*args)

This final style is quite common in the standard library and major Python tools. *args denotes a variable number of arguments, so you can use this function as

repeat(4, foo, "test")

or

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

repeat(10, inquisition, "surprise", "fear", "ruthless efficiency")

Note that I put the number of repetitions up front for convenience. It can't be the last argument if you want to use the *args construct.

(For completeness, you could add keyword arguments as well with **kwargs.)

You will need to pass the parameters for foo, to the repeat function:

#! /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)
Peter Sichel

While many of the answers here are good, this one might be helpful because it doesn't introduce any unnecessary repetition and the reason for callbacks in the first place is often to synchronize with other work outside of the main UI thread.

Enjoy!

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!