【问题标题】:Anonymous callback functions in Python 2.7.5?Python 2.7.5 中的匿名回调函数?
【发布时间】:2014-01-07 13:09:16
【问题描述】:

我正在尝试使用 python 2.7.5 在 wxPython 应用程序中解耦 GUI 和逻辑。由于 wxPython 使用事件绑定,我想我会扩展这种方法。总结我的代码:

GUI.py

class MainInterface():
    def __SetupControlPanel(self, controlPanel):
        self.DoSomethingButton = wx.Button(controlPanel, wx.ID_ANY, "Do something")

    def BindCallback_DoSomething(self, callback):
        self.frame.Bind(wx.EVT_BUTTON, callback, self.DoSomethingButton)

main.py

def DoSomething(event):
    someLogicClass.DoSomething()

interface.BindEvent_DoSomething(DoSomething)

这很好地解耦了应用程序的两个部分,但我不喜欢在 main.py 中为每个回调定义一个单独的函数的方式,因为它通常只调用一个逻辑函数。从 JS 的背景来看,我已经习惯了能够使用匿名函数。我想这样的事情会让我的代码更加紧凑:

interface.BindEvent_DoSomething(def (event):
    someLogicClass.DoSomething()
)

有没有办法在 Python 中实现这样的语法?

【问题讨论】:

  • 你搜索过“python匿名函数”吗?
  • 我有,但我发现的 lambda 函数示例都没有表明可以简单地调用一个方法......我猜我错过了。谢谢。

标签: python events callback wxpython anonymous-function


【解决方案1】:

您可以尝试使用 lambda 函数:

interface.BindEvent_DoSomething(lambda event: someLogicClass.DoSomething())

【讨论】:

    【解决方案2】:

    你可以使用 lambda 函数

    interface.BindEvent_DoSomething(lambda e: doSomething())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      相关资源
      最近更新 更多