将参数传递给包回调

时间:2019-11-24 22:02:08

标签: python callback

我正在使用Pynput包来监听键盘按键。它具有我定义的按键按下方法:

def on_press(key):
    print('{0} key pressed'.format(key.char))
    ...
    if key == ord('q'):
        exit(0)
        return
    # view.update_ui(player.get_metadata()) # how can I pass this in?

然后将其连接到侦听器并启动侦听器:

listener = keyboard.Listener(on_press=on_press)
listener.start()

如Pynput文档中所示,如果唯一的参数为key,则此方法非常有用。但是,我希望此函数采用其他参数,例如def on_press(key, view, player)。进行此操作最有效的方法是什么?

1 个答案:

答案 0 :(得分:2)

可能是工厂功能或functools.partial

from functools import partial

def on_press(key, view, player):
    print('{0} key pressed'.format(key.char))
    ...
    if key == ord('q'):
        exit(0)
        return

listener = keyboard.Listener(on_press=partial(on_press, view=my_view, player=some_player))
listener.start()