question about scope

Steve Holden steve at holdenweb.com
Sun Oct 1 01:05:04 EDT 2006


John Salerno wrote:
> I have the following code:
> 
> 
> 
> class DataAccessFrame(wx.Frame):
> 
>      menu_items = [('File', 'New Database', 'New Record', 'Open 
> Database...',
>                     'Open Record...', 'Save Record', 'Save All Records',
>                     'Close Record', 'Close Database'),
>                    ('Edit', 'Undo', 'Redo', 'Cut', 'Copy', 'Paste'),
>                    ('Help',)]
> 
>      def __init__(self):
>          wx.Frame.__init__(self, None, title='Database Access Panel')
>          panel = wx.Panel(self)
>          self.create_menubar()
> #       notebook = wx.Notebook(panel)
> 
> #       sizer = wx.BoxSizer()
> #       sizer.Add(notebook, 1, wx.EXPAND)
> #       panel.SetSizer(sizer)
> 
>      def create_menubar(self):
>          menubar = wx.MenuBar()
>          for item in self.menu_items:
>              menu = wx.Menu()
>              menubar.Append(menu, item[0])
>              for subitem in item[1:]:
>                  menu.Append(-1, subitem)
>          self.SetMenuBar(menubar)
> 
> In the create_menubar method, I got an error about the global name 
> "menu_items" not being defined, and this was fixed by putting "self." in 
> front of the variable name.
> 
> But why is this necessary? Doesn't a method look in its enclosing class, 
> or is that not one of the levels of scope?

The methods do indeed look in their enclosing class, but only for 
self-relative references. These are sought first in the instance, then 
in the instance's class, then in the instance's class's superclass, and 
so on up to the ultimate superclass. In other words, all attribute 
lookup uses the method resolution order ...

You can also reference class variables relative to the class name (i.e. 
you could have used DataAccessFrame.menu_items) but that loses a lot of 
flexibility.

Also note that when you bind a value to a self-relative name, that 
binding *always* occurs in the instance's namespace. Some people don't 
like that, but it's a fact of life that others use to provide instance 
defaults in class variables that are shadowed by an instance variable 
after a first assignment.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list