Need help with Python scoping rules

Xavier Ho contact at xavierho.com
Thu Aug 27 21:16:41 EDT 2009


On Fri, Aug 28, 2009 at 9:49 AM, kj <no.email at please.post> wrote:

>
> Miles Kaufmann <milesck at umich.edu> writes:
>
> >...because the suite
> >namespace and the class namespace would get out of sync when different
> >objects were assigned to the class namespace:
>
> >class C:
> >   x = 1
> >   def foo(self):
> >       print x
> >       print self.x
>
> > >>> o = C()
> > >>> o.foo()
> >1
> >1
> > >>> o.x = 2
> > >>> o.foo()
> >1
> >2
>

I haven't tested either codes, but that isn't "out of sync". Your x = 1 is a
static variable, and shared between all isntances of class C.


> 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
>
> which would lead to exactly the same thing.
>

It works because you're simply explicitly referring to the class's local
scope, which leads to the same result.

Again, that's just my understanding of the implementation.

Cheers,
Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090828/dafd8c5a/attachment.html>


More information about the Python-list mailing list