Python:绑定未绑定的方法? [英] Python: Bind an Unbound Method?
问题描述
在Python中,有没有办法绑定一个未绑定的方法而不调用它?
In Python, is there a way to bind an unbound method without calling it?
我编写一个wxPython程序, d很好将所有我的按钮的数据组合为一个类级别的元组列表,例如:
I am writing a wxPython program, and for a certain class I decided it'd be nice to group the data of all of my buttons together as a class-level list of tuples, like so:
class MyWidget(wx.Window):
buttons = [("OK", OnOK),
("Cancel", OnCancel)]
# ...
def Setup(self):
for text, handler in MyWidget.buttons:
# This following line is the problem line.
b = wx.Button(parent, label=text).Bind(wx.EVT_BUTTON, handler)
问题是,因为 handler
的所有值都是未绑定的方法,我的程序在一个壮观的火焰中爆炸,我哭了。
The problem is, since all of the values of handler
are unbound methods, my program explodes in a spectacular blaze and I weep.
我在网上寻找一个解决方案,似乎应该是一个相对直接,可解决的问题。不幸的是我找不到任何东西。现在,我使用 functools.partial
来解决这个问题,但是有没有人知道是否有一个干净,健康,Pythonic的方式绑定一个未绑定的方法
I was looking around online for a solution to what seems like should be a relatively straightforward, solvable problem. Unfortunately I couldn't find anything. Right now, I'm using functools.partial
to work around this, but does anyone know if there's a clean-feeling, healthy, Pythonic way to bind an unbound method to an instance and continue passing it around without calling it?
推荐答案
所有函数也都是描述符可以通过调用 __ get __
方法绑定它们:
All functions are also descriptors, so you can bind them by calling their __get__
method:
bound_handler = handler.__get__(self, MyWidget)
这里是R. Hettinger的优秀指南到描述符。
Here's R. Hettinger's excellent guide to descriptors.
这篇关于Python:绑定未绑定的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!