Nested scopes hitch

Marek Augustyn maug at poczta.onet.pl
Fri Apr 5 12:31:47 EST 2002


Hi,

Would somebody explain the following behavior (Python 2.2)?

Function nested in class:
(why nested scoping doesn't work?)

class A:
    a = 1
    def f():
        print a
    f()

result:

Traceback (most recent call last):
  File "c.py", line 1, in ?
    class A:
  File "c.py", line 5, in A
    f()
  File "c.py", line 4, in f
    print a
NameError: global name 'a' is not defined

and version with function nested in function:
(nested scoping works perfectly)

def f1():
    a = 1
    def f2():
        print a
    f2()
f1()

result:

1
---------------

A bit of explanation:
I want a singleton class object (no object instances), and a function to do
some initialization when class object is created. Is it (first example) the
proper way to achieve it?

Regards,
August





More information about the Python-list mailing list