Need help with Python scoping rules

Stephen Fairchild somebody at somewhere.com
Thu Aug 27 22:23:00 EDT 2009


kj wrote:

> But this unfortunate situation is already possible, because one
> can already define
> 
> class C:
>     x = 1
>     def foo(self):
>         print C.x
>         print self.x

How is this a problem? There is no ambiguity between the global scope and
the local from within foo.

>From within foo C is accessed from the global scope having not found it as a
local. Once you have C C.x is just one step away. 

Variable self is local to function foo since it was passed in as a parameter
from the method which wraps it. 

Variable self refers to a class instance which contains a dictionary.
Variable x is absent from the instance dictionary so the class
self.__class__ is referenced, again from local scope to find x. If it
wasn't found there the superclasses would have been searched before
throwing an attribute error.

It seems to me, you are confusing instance creation with class creation.
-- 
Stephen Fairchild



More information about the Python-list mailing list