相关疑难解决方法(0)

Python:绑定一个未绑定的方法?

在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)
Run Code Online (Sandbox Code Playgroud)

问题是,由于所有的值handler都是未绑定的方法,我的程序在一个壮观的火焰中爆炸,我哭泣.

我在网上寻找解决方案似乎应该是一个相对简单,可解决的问题.不幸的是我找不到任何东西.现在,我正在functools.partial尝试解决这个问题,但有没有人知道是否有一种干净,健康,Pythonic的方式将未绑定的方法绑定到一个实例并继续传递它而不调用它?

python methods bind class

108
推荐指数
4
解决办法
4万
查看次数

在Python 3中获取未绑定方法对象的定义类

假设我想为类中定义的方法创建装饰器.我希望装饰器在被调用时能够在定义方法的类上设置属性(以便将其注册到用于特定目的的方法列表中).

在Python 2中,该im_class方法很好地完成了这个:

def decorator(method):
  cls = method.im_class
  cls.foo = 'bar'
  return method
Run Code Online (Sandbox Code Playgroud)

但是,在Python 3中,似乎不存在这样的属性(或替代它).我想这个想法是你可以调用type(method.__self__)来获取类,但是这对于未绑定的方法不起作用,因为__self__ == None在那种情况下.

注意:这个问题实际上与我的情况有点无关,因为我选择在方法本身上设置属性,然后让实例扫描其所有方法,在适当的时间查找该属性.我(目前)也在使用Python 2.6.但是,我很好奇是否有替换版本2的功能,如果没有,那么完全删除它的理由是什么.

编辑:我刚发现这个问题.这使得看起来最好的解决方案就是像我一样避免它.我仍然想知道为什么它被删除了.

python python-3.x

35
推荐指数
3
解决办法
2万
查看次数

Python:如何使用其他类型参数调用未绑定方法?

Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
...     def f(self):
...             print self.k
...
>>> class B(object):pass
...
>>> a=A()
>>> b=B()
>>> a.k="a.k"
>>> b.k="b.k"
>>> a.f()
a.k
>>> A.f(a)
a.k
>>> A.f(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with A instance as first argument (got B instance instead)
>>>
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点? …

python methods

5
推荐指数
1
解决办法
2791
查看次数

标签 统计

python ×3

methods ×2

bind ×1

class ×1

python-3.x ×1