相关疑难解决方法(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 __getattr__的行为与Python 2不同?

我需要编写一个实现32位无符号整数的类,就像它们在C编程语言中一样.我最关心的是二元转换,但我通常希望我的班级:

  1. 具有相同的接口,int具有与工作int正常
  2. 我的U32类(int + U32,U32+ int等)的任何操作也返回U32
  3. 是纯python - 我不想使用NumPy,ctypes等.

正如在这个答案中可以找到的,我得到了一个在Python 2下运行的解决方案.最近我尝试在Python 3下运行它并注意到虽然以下测试代码在旧版本的Python下工作正常,但Python 3引发了一个错误:

class U32:
    """Emulates 32-bit unsigned int known from C programming language."""

    def __init__(self, num=0, base=None):
        """Creates the U32 object.

        Args:
            num: the integer/string to use as the initial state
            base: the base of the integer use if the num given was a string
        """
        if base is None:
            self.int_ = int(num) % 2**32
        else:
            self.int_ = …
Run Code Online (Sandbox Code Playgroud)

python

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

标签 统计

python ×2

bind ×1

class ×1

methods ×1