Skip to content Skip to sidebar Skip to footer

When Is "self" Required?

I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo. However, I'm looking through the wxPython in Action

Solution 1:

In those instances, if you do not use self then you will create only a local variable of that name. In the first example, panel is created as a local variable and then referenced later in the function, but it won't be available outside that function. The act of passing self to the wx.Panel constructor associated it with the current object in some fashion, so it doesn't just disappear when the function returns.

Solution 2:

self is always required when referring to the instance itself, except when calling the base class constructor (wx.Frame.__init__). All the other variables that you see in the examples (panel, basicLabel, basicText, ...) are just local variables - not related to the current object at all. These names will be gone when the method returns - everything put into self.foo will survive the end of the method, and be available in the next method (e.g. self.button).

Post a Comment for "When Is "self" Required?"