在实例之间创建共享成员变量(静态)

时间:2015-10-05 04:12:22

标签: python

阅读https://stackoverflow.com/a/69067/1767754后我知道

1)Python中的静态成员与C ++中的静态成员不同

2)只有新创建的实例才具有静态变量的最新值同步值

class Test:
    var = 3
    def __init__(self):
        pass

a = Test()
print "a " +  str(a.var) #output: 3
Test.var = 5
b = Test()
print "b " + str(b.var) #output: 5
print "a " + str(a.var) #output: 3 not synced with static member

那么在类实例之间共享成员变量的常用方法是什么?如何创建一个包含共享数据的全局类?那样:

class Globals:
    var = 3
class Test:
    def setVar(self, var):
        Globals.var = var

test = Test()
test.setVar(3)
print Globals.var

1 个答案:

答案 0 :(得分:3)

  

只有新创建的实例才具有静态变量的最新值同步值

不正确。也许你会混淆以下行为:

class Test:
    var = 3
    def __init__(self):
        pass

a = Test()
print "a " +  str(a.var)
Test.var = 5
b = Test()
print "b " + str(b.var)
print "a " + str(a.var)

输出:

a 3
b 5
a 5

的行为

class Test:
    var = 3
    def __init__(self):
        pass

a = Test()
print "a " +  str(a.var)
a.var = 2   # Making var a member of the instance a
Test.var = 5
b = Test()
print "b " + str(b.var)
print "a " + str(a.var)
a 3
b 5
a 2

在第二种情况下,var不仅是T的静态成员,它还是实例a的成员。