Why no lexical scoping for a method within a class?

Chris Rebert clp at rebertia.com
Thu Dec 18 01:15:29 CET 2008


On Wed, Dec 17, 2008 at 4:03 PM, Rhodri James
<rhodri at wildebst.demon.co.uk> wrote:
> On Wed, 17 Dec 2008 15:19:32 -0000, walterbyrd <walterbyrd at iname.com> wrote:
>
>> However in the methods are within a class, the scoping seems to work
>> differently.
>
> Not really.  Hopefully this commentary will show you why.
>
>> class ab():
>>    def a(self):
>>        self.x = 99
>>        print self.x
>>    def b(self):
>>        print self.x
>>
>> i = ab()
>
> This creates |i|, an instance of class |ab|.  As yet it is pure and virgin,
> having nothing but the methods that it gets from |ab|.  Soon this will
> change...
>
>> i.a()
>
> This creates an attribute |x| in |i|, and assigns the number 99 to it.
>
>> i.b() # this works, why no lexical scoping?
>
> This works because you ran |i.a()| first, so |i.x| exists and can be printed
> out.  Lexical scoping is going on here, you're just mistaking what's being
> scoped; it's the |self| in |b|, which is in scope because it's a parameter.
>  This particular |self| (the |i| you made earlier) happens to have an
> attribute |x|, so it all works.  If however you'd written:
>
> j = ab()
> j.b()
>
> then Python would whinge mightily at you, claiming that it knoweth naught of
> this |x| attribute of which you speak, and can it go home now for this is a
> silly place.  The |self| in |b| is still in lexical scope, though.
>

Relatedly, Python has no notion of 'declaring' instance variables in a
class (instead, you just create them in __init__ or other methods),
and class variables (in Java terminology: 'static' variables) do not
constitute a scope for variable lookup.
Python is still lexically scoped, it's just that only functions and
the "globals"/toplevel/module-level constitute scopes, not class
bodies.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list