question about scope

Steve Holden steve at holdenweb.com
Sun Oct 1 08:41:37 EDT 2006


John Salerno wrote:
> Steve Holden wrote:
> 
> 
>>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 ...
> 
> 
> So what I did is correct? It does work, but why don't I have to define 
> the list as self.menu_items as well?

The first point is that the name "self" isn't in scope at the point you 
make the assignment: it's a local variable (strictly, it's a parameter, 
but they are treated the same as locals) to each method, and when the 
method is called it's a reference to the specific instance whose method 
was called (technically, the instance o which the method is bound).

You could assign self.menu_items in the __init__() method, but it 
wouldn't really have any advantages given that names in class scope are 
reachable via the name resolution mechanism.

Note that the def statement is also executed in class scope, which is 
why the method names are class-relative. Python has a special method 
binding feature that changes a call like

     instance.method(a1, a2)

into

     (instance.__class__).method(instance, a1, a2)

This is where the reference to self "magically" appears from in method 
calls.

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