Why no lexical scoping for a method within a class?

rdmurray at bitdance.com rdmurray at bitdance.com
Wed Dec 17 11:04:42 EST 2008


Quoth walterbyrd <walterbyrd at iname.com>:
> For a language as well structured as Python, this seems somewhat
> sloppy, and inconsistant.  Or is there some good reason for this?

Yes.  It's called Object Oriented Programming.

> 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 x is an attribute.

If you don't understand what that means, read any introductory
article on OOP.

To give you a clue, if you had said:

    class ab():
        def a(self):
            x = 99
            print x
        def b(self):
            print x
        
You'd have gotten the exception you expected (assuming x wasn't
defined globally).

--RDM




More information about the Python-list mailing list