Python:绑定一个未绑定的方法? [英] Python: Bind an Unbound Method?

查看:31
本文介绍了Python:绑定一个未绑定的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,有没有一种方法可以在不调用的情况下绑定未绑定的方法?

In Python, is there a way to bind an unbound method without calling it?

我正在编写一个 wxPython 程序,对于某个类,我决定将所有按钮的数据组合在一起作为一个类级别的元组列表会很好,如下所示:

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.

作为从 Keith's 中提取的独立示例 评论:

As a self-contained example pulled from Keith's comment:

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

这篇关于Python:绑定一个未绑定的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆