newbie question on class vars

JXSternChangeX2R JXSternChangeX2R at gte.net
Mon Oct 7 15:09:31 EDT 2002


I'm trying to define a global var for the class.  This gets an error:
SyntaxError: invalid syntax
Traceback (most recent call last):
  File "C:/Hax/HMon/dbclasses/foo.py", line 16, in ?
    f.fn1()
  File "C:/Hax/HMon/dbclasses/foo.py", line 6, in fn1
    print __gvar
NameError: global name '_foo__gvar' is not defined

I guess I'm missing something basic about globals.  Help?

Gotta get a good newbie book, the online doc ain't helping at all.

Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on
win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help

On XP Pro, if that matters.

Thanks.

J.


#------------------------------
class foo:
    __gvar = 1

    def fn1(self):
        print __gvar

    def fn2(self):
        __gvar += 1
        print __gvar

#------------------------------

f = foo()

f.fn1()
f.fn2()
f.fn1()

f = None


----------------------------------------------------------

late bulletin:  saying "self.__gvar" inside fn1 and fn2 fixes, but I
thought the idea was to avoid saying "self." all the time.

another late bulletin:  saying "global" gets no syntax error, but I
can't figure any way to reference from inside fn1:

    global __gvar 

    def fn1(self):
        print __gvar

gets error:
Traceback (most recent call last):
  File "C:\Hax\HMon\dbclasses\foo.py", line 29, in ?
    f.fn1()
  File "C:\Hax\HMon\dbclasses\foo.py", line 7, in fn1
    print __gvar
NameError: global name '_foo__gvar' is not defined






More information about the Python-list mailing list