Nested scopes hitch
Jeff Shannon
jeff at ccvcorp.com
Fri Apr 5 14:49:16 EST 2002
In article <a8kn23$ikq$1 at zeus.polsl.gliwice.pl>,
maug at poczta.onet.pl says...
>
> class A:
> a = 1
> def f():
> print a
> f()
> Traceback (most recent call last):
[...]
> NameError: global name 'a' is not defined
>
> def f1():
> a = 1
> def f2():
> print a
> f2()
> f1()
[...]
> 1
The difference here is because of the class statement, it's not
using nested scopes in the sense that you're thinking. In class
A, the attribute a is a class attribute, not a name in an
enclosing scope, so the nested scope rules don't apply. You can
access it by referring to self.a, however -- that will find both
instance and class attributes.
>>> class A:
... a = 1
... def f(self):
... print self.a
...
>>> obj = A()
>>> obj.f()
1
>>>
However, for your desired purpose -- a singleton "class" with no
instances -- you're probably better off putting your code in a
separate module, and importing the module wherever needed-- as
noted in another thread today, a module is already a singleton.
--
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list