Search code examples
pythonwxpython

Using "self" in Python and wxPython


I am currently reading a popular publication about wxPython. In the code listed below, used to create 2 different wx.Frame subclasses, the use of "self" seems confusing and inconsistent to me. The variables in the first code example have self in front of them while the variables in the second code example do not. Why would one choose to use self and when would it not be required/appropriate.

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)

Solution

  • In general (this is a rephrasing of @roippi's comment), saying self.panel = ... makes it so you can access self.panel later on. It stores the data long-term. But if you typed panel = ..., you wouldn't be able to access a variable called panel outside of this method.