Re: Why no lexical scoping for a method within a class?



On Wed, 17 Dec 2008 15:19:32 -0000, walterbyrd <walterbyrd@xxxxxxxxx> 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
.



Relevant Pages

  • Problem with Lexical Scope
    ... I am not completely knowledgable about the status of lexical scoping in ... Python, but it was my understanding that this was added in a long time ... def collect: ...
    (comp.lang.python)
  • Lexical Scope
    ... I must be misunderstanding how Python 2.3 handles lexical scoping. ... def run: ...
    (comp.lang.python)
  • Re: Lexical Scope
    ... On Thursday 30 October 2003 07:59 am, Matt Knepley wrote: ... > I must be misunderstanding how Python 2.3 handles lexical scoping. ... variables of the same name in outer scopes. ... > def run2: ...
    (comp.lang.python)
  • Why no lexical scoping for a method within a class?
    ... sloppy, and inconsistant. ... Or is there some good reason for this? ... def a: ... i.b# this works, why no lexical scoping? ...
    (comp.lang.python)
  • text adventure question
    ... I am working on a text adventure game for python to get back into ... def character_sheet: ... global reputation ... print "Please choose another command. ...
    (comp.lang.python)