Why no lexical scoping for a method within a class?

John Machin sjmachin at lexicon.net
Wed Dec 17 16:54:26 CET 2008


On Dec 18, 2:19 am, walterbyrd <walterb... at iname.com> wrote:
> For a language as well structured as Python, this seems somewhat
> sloppy, and inconsistant.  Or is there some good reason for this?
>
> Here is what I mean:
>
> def a():
>     x = 99
>     print x
>
> def b():
>     print x
>
> a()
> b() # raises an exception because x is not defined.
>
> However in the methods are within a class, the scoping seems to work
> differently.
>
> class ab():
>     def a(self):
>         self.x = 99
>         print self.x
>     def b(self):
>         print self.x
>
> i = ab()
> i.a()
> i.b() # this works, why no lexical scoping?

Two questions for you:
(1) If you were to change the sloppy inconsistent scoping mechanism in
classes, what would you change it to?
(2) What do you think of the following:
 class ab():
     def a(self):
         self.x = 99
         print self.x
     def b(me):
         print me.x
 ?



More information about the Python-list mailing list