[Tutor] Variable scope for class?
Kent Johnson
kent37 at tds.net
Fri Aug 31 01:52:11 CEST 2007
Dave Kuhlman wrote:
> So far so good. But, here is the one I do not understand.
>
> G1 = 111
> class A(object):
> G1 = 222
> def show(self):
> print G1
>
> def test():
> a = A()
> a.show()
>
> test()
>
> But, when I run this I see "111", not "222".
>
> Why is that? "G1 = 222" is in the enclosing scope, right?
>
> Well, I guess that is wrong. Apparently in Python, a class does
> not create an enclosing scope.
Right. The class statement creates a temporary local namespace that is
used to initialize the __dict__ of the class. Names in this namespace
can be accessed directly while the class statement is executing; after
that they have to be accessed as attributes of the class or an instance.
Kent
More information about the Tutor
mailing list