【问题标题】:Redefine an existing function重新定义现有功能
【发布时间】:2014-02-13 23:51:44
【问题描述】:

我这样定义PyControl 的子类:

class MyBitmapButton(wx.PyControl):
    def __init__(self, parent, id=-1, bmp=None, label='blah', pos = wx.DefaultPosition, size=(166,220), style = 0, validator = wx.DefaultValidator,
                 name = "mybitmapbutton"):
        style |= wx.BORDER_NONE 
        wx.PyControl.__init__(self, parent, id, pos, size, style, validator, name)
        self.myimg = wx.StaticBitmap(self, -1, bmp, pos=(8,8), size=(150,150))
        self.mytxt = wx.StaticText(self, -1, label, (6,165))

    def Bind(self, *args, **kwargs):
        self.Bind(*args, **kwargs)         # infinite recursion problem ! 
        self.myimg.Bind(*args, **kwargs)
        self.mytxt.Bind(*args, **kwargs)

我想覆盖标准Bind,但在这个定义中,我需要使用old绑定(由wx.PyControl提供)。

使用当前代码,我遇到了infinite recusion loop 问题:

如何在new Bind 的定义中重用old Bind

【问题讨论】:

  • 两个答案同时出现,质量相同,所以我真的不知道该选择哪个答案?抱歉,我给了 2 个答案之一,我随机给出了“接受为答案”!

标签: python class wxpython subclass


【解决方案1】:

你需要在这里使用super,来访问超类的Bind版本:

super(MyBitmapButton, self).Bind(*args, **kwargs)

或者,在 Python 3 中,只是

super().Bind(*args, **kwargs).

【讨论】:

    【解决方案2】:

    将此行self.Bind(*args, **kwargs) 更改为:

    super(MyBitmapButton, self).Bind(*args, **kwargs)
    

    在 python3 中 super 将在没有参数的情况下工作:

    super().Bind(*args, **kwargs)
    

    来自super docs

    返回一个代理对象,它将方法调用委托给父对象或 类型的兄弟类。这对于访问继承的方法很有用 已在类中被覆盖。搜索顺序同上 由 getattr() 使用,但类型本身被跳过。
    ...

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 2020-03-17
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 2021-01-11
      • 1970-01-01
      • 2012-09-05
      相关资源
      最近更新 更多