Why no lexical scoping for a method within a class?

Diez B. Roggisch deets at nospam.web.de
Wed Dec 17 10:41:09 EST 2008


walterbyrd 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?

Because what you do is to create instance variables. Why do you expect them
not working if you explicitly access them?

The real analog of your example would be this:

class ab():
   def a(self):
       x = 100
       print x

   def b(self):
       print x

which provokes the same error.

however, there *are* different scoping rules, classes don't create a lexical
scope for their own variables:


class foo(object):
    x = 100

    def a(self):
        print x


Diez



More information about the Python-list mailing list