Python:绑定未绑定方法?

发布于 2021-02-02 23:11:53

在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的方式将未绑定的方法绑定到实例并继续传递它而不调用它吗?

关注者
0
被浏览
85
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    所有函数也是描述符,因此你可以通过调用它们的__get__方法来绑定它们:

    bound_handler = handler.__get__(self, MyWidget)
    

    这是R. Hettinger 关于描述符的出色指南。

    作为一个独立的例子,请参考Keith的 评论:

    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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看