[Tutor] OOP / Classes questions

Steve Willoughby steve at alchemy.com
Fri Apr 10 20:53:02 CEST 2009


On Fri, Apr 10, 2009 at 08:44:37PM +0200, Stefan Lesicnik wrote:
> I am a relative newbie to python and OOP concepts and am trying to
> work through wxpython. I've seen understanding classes is essential to
> this and have been trying to work through them.

Welcome!  If you're really new, wxpython may be a bit advanced, so if
it feels like you're just not getting what's going on, you might want
to step back a level and try simpler projects and work back up to this.

> 1. I am not sure why / when you use the self. notation.  I understand
> that self refers to the instance you create, so you can have multiple
> instances and the class knows which one you are talking about.
> Why do they use self.Bind or similar and at other times use file =
> (without the self)

Inside the definition of a class method such as MenuExample.__init__()
in your included code (and thank you, by the way, for including actual
code to discuss!), if you assign to a variable such as
  file = wx.Menu()
this is referring to a *local* variable "file" which will exist as
long as the __init__() method is actually running (each time) and 
then get deleted when that function finishes running.  It's a temporary
variable, in other words. 

On the other hand, something like
  self.file = wx.Menu()
would store this in an *instance* variable "self.file" which will exist
as long as that object instance does, stored into the object itself
so to speak.

Calling a method like
  self.Bind(...)
means to invoke the Bind method on this same object instance.  If
you wanted to call the Bind method on object foo, you'd say foo.Bind()
so this is the same thing, just referring to the same object that's
in the middle of its own __init__() call at the time.

> 2. In the Bind( they use self.OnQuit which seems to call the function
> OnQuit). Again, why is it self.OnQuit?

Because it's not simply a function, it's a method of the class, and
specifically you're asking the individual object "self" to perform
its OnQuit action.

> 3. def OnQuit(self, event): - where does event here come from and what
> does it do with it?

Here's one reason I said wxpython is pretty advanced.  GUI code tends
to be event-driven, so as the user triggers events such as clicking
on buttons or typing keys, those events cause methods to be called
in the objects controlling those on-screen widgets.  So if, say, the
user clicked a "quit" button, WX says that a button-press event 
occurred, and will call the OnQuit method here with information about
the event in the object called "event".  Your method could just ignore
that parameter if you don't care about that, or you could examine it
to see details as to what event led you to the OnQuit action.
 

-- 
Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.


More information about the Tutor mailing list