Bug in Python class static variable?

Bruza benruza at gmail.com
Mon Jul 2 06:39:18 EDT 2007


I am trying to define a class static variable. But the value of the
static variable seems to be only defined inside the file that the
class is declared. See the code below. When I run "python w.py", I
got:

000=======> Hello World
001=======> Hello World
002=======> Not Initialized
003=======> Not Initialized
004=======> Not Initialized
005=======> Hello World

Looks like even though the class variable "ClassW.w_classStaticVar"
was set inside "startup()", the value never carried over to functions
in "a.py". Is this a bug in Python's static variable handling. I am
running Python 2.4.4.


Ben


#===== file: w.py ========
from a import *

class ClassW:
    w_classStaticVar = "Not Initialized"

    def initA(self):
        print "001=======>", ClassW.w_classStaticVar
        obj = ClassA()
        obj.init2()
        print "005=======>", ClassW.w_classStaticVar

def startup():
    ClassW.w_classStaticVar = "Hello World"
    wo = ClassW()
    print "000=======>", ClassW.w_classStaticVar
    wo.initA()

if __name__ == '__main__':
    startup()

#===== file: a.py ========
from w import *

class ClassA:
    def __init__(self):
        print "002=======>", ClassW.w_classStaticVar

    def init2(self):
        print "003=======>", ClassW.w_classStaticVar
        w = ClassW()
        print "004=======>", ClassW.w_classStaticVar




More information about the Python-list mailing list