Re: Why no lexical scoping for a method within a class?
- From: "Rhodri James" <rhodri@xxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 18 Dec 2008 00:03:01 -0000
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():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...
def a(self):
self.x = 99
print self.x
def b(self):
print self.x
i = ab()
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
.
- References:
- Why no lexical scoping for a method within a class?
- From: walterbyrd
- Why no lexical scoping for a method within a class?
- Prev by Date: Re: The rule of literal string
- Next by Date: Re: The rule of literal string
- Previous by thread: Re: Why no lexical scoping for a method within a class?
- Next by thread: Re: Why no lexical scoping for a method within a class?
- Index(es):
Relevant Pages
|