function - 使用回调函数传递附加参数

标签 function callback urwid

以下示例(取自此处:http://urwid.org/tutorial/index.html)展示了如何将键值传递给回调函数show_or_exit

import urwid

def show_or_exit(key):
    if key in ('q', 'Q'):
        raise urwid.ExitMainLoop()
    txt.set_text(repr(key))

txt = urwid.Text(u"Hello World")
fill = urwid.Filler(txt, 'top')
loop = urwid.MainLoop(fill, unhandled_input=show_or_exit)
loop.run()

如何使用取决于系统状态的回调将另一个参数传递给 show_or_exit ,就像这样?

...: param_val = 4
...:
...: def my_fun():
...:     #do something
...:     return param_val
...:
...: def show_or_exit(key, param_val):
...:     if key in ('q', 'Q'):
...:         raise urwid.ExitMainLoop()
...:     txt.set_text(repr(key))
...:     do_something(param_val)
...:
...: txt = urwid.Text(u"Hello World")
...: fill = urwid.Filler(txt, 'top')
...: loop = urwid.MainLoop(fill, unhandled_input=show_or_exit)
...: loop.run()

最佳答案

因此,有多种方法可以做到这一点。您可以使用全局变量,但我想您可能会问这个问题,因为您想要一种更好的方法来做到这一点(另外,全局变量无论如何都会笨拙地改变状态)。

对于像本例这样的小程序,一种技术可能是使用一个全局对象来存储状态:

import urwid
from functools import partial


class State(object):
    param1 = 1
    param2 = 'ola'

    def __repr__(self):
        return 'State(param1={}, param2={})'.format(self.param1, self.param2)


def show_or_exit(app_state, key):
    if key in ('q', 'Q'):
        raise urwid.ExitMainLoop()
    app_state.param1 += 1
    txt.set_text('key: {!r} state: {!r}'.format(key, app_state))


txt = urwid.Text(u"Hello World")
fill = urwid.Filler(txt, 'top')
app_state = State()
callback = partial(show_or_exit, app_state)
loop = urwid.MainLoop(fill, unhandled_input=callback)
loop.run()

出于说明目的,我将这个示例保持最小,但是 State 类将从 using the attrs library 中受益匪浅。 。强烈推荐! :)

对于更复杂的程序,我建议构建支持回调事件的自定义小部件并单独管理状态:您可以看到 an example of implementing that in this solitaire game .

关于function - 使用回调函数传递附加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49162143/

相关文章:

Python ncurses、CDK、urwid 的区别

Python3 : purge exception chain?

vue.js - 外部付款后使用 POST 重定向到前端 URL

javascript - 尝试理解 Javascript 中参数数组的概念

c++ - 如何将未知大小的二维数组传递给函数

algorithm - 在 F# 中创建不超过某个值的列表或数字序列

android - Fragment 中处理信息的通知 Activity

linux - 如何使用 urwid 和 asyncio 使长任务非阻塞?

php - explode 后在PHP上获取剩余的拆分字符串

function - 从一个函数返回两种不同的类型