Why no lexical scoping for a method within a class?

Rhodri James rhodri at wildebst.demon.co.uk
Thu Dec 18 01:03:01 CET 2008


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.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list