在Python中,有没有一种方法可以绑定未绑定的方法而不调用它?
我正在编写一个 wxPython 程序,对于某个类,我决定将所有按钮的数据分组在一起作为类级元组列表,如下所示:
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
是未绑定的方法,我的程序在一场壮观的大火中爆炸,我哭了。
我在网上寻找一个似乎应该是相对简单、可解决的问题的解决方案。不幸的是我什么也没找到。现在,我正在使用functools.partial
来解决这个问题,但是有谁知道是否有一种干净、健康、Pythonic 的方式将未绑定的方法绑定到实例并继续传递它而不调用它?
所有功能也都描述符,所以你可以通过调用它们来绑定它们__get__
method:
bound_handler = handler.__get__(self, MyWidget)
这是 R. Hettinger 的精彩作品guide https://docs.python.org/2/howto/descriptor.html到描述符。
作为一个独立的例子Keith's https://stackoverflow.com/users/834176/keith-pinson comment https://stackoverflow.com/questions/1015307/python-bind-an-unbound-method#comment8431145_1015405:
def bind(instance, func, as_name=None):
"""
Bind the function *func* to *instance*, with either provided name *as_name*
or the existing name of *func*. The provided *func* should accept the
instance as the first argument, i.e. "self".
"""
if as_name is None:
as_name = func.__name__
bound_method = func.__get__(instance, instance.__class__)
setattr(instance, as_name, bound_method)
return bound_method
class Thing:
def __init__(self, val):
self.val = val
something = Thing(21)
def double(self):
return 2 * self.val
bind(something, double)
something.double() # returns 42
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)