在Python和wxPython中使用"self

1 投票
1 回答
923 浏览
提问于 2025-04-18 18:54

我现在正在阅读一本关于wxPython的热门书籍。在下面的代码中,创建了两个不同的wx.Frame子类,我觉得里面的“self”用法有点让人困惑和不一致。在第一个代码示例中,变量前面都有self,而在第二个代码示例中则没有。为什么有的地方要用self,而有的地方又不需要呢?

class MouseEventFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Frame With Button',size=(300, 100))
        self.panel = wx.Panel(self)
        self.button = wx.Button(self.panel,label="Not Over", pos=(100, 15))
        self.Bind(wx.EVT_BUTTON, self.OnButtonClick,self.button)
        self.button.Bind(wx.EVT_ENTER_WINDOW,self.OnEnterWindow)
        self.button.Bind(wx.EVT_LEAVE_WINDOW,
        self.OnLeaveWindow)


class InsertFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Frame With Button',size=(300, 100))
        panel = wx.Panel(self)
        button = wx.Button(panel, label="Close", pos=(125, 10),size=(50, 50))
        self.Bind(wx.EVT_BUTTON, self.OnCloseMe, button)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

1 个回答

0

一般来说(这是对@roippi评论的重新表述),说 self.panel = ... 的意思是你可以在之后的代码中访问 self.panel。它会把数据长期保存下来。但是如果你写的是 panel = ...,那么在这个方法之外你就无法访问到叫 panel 的变量了。

撰写回答