1

After reading https://stackoverflow.com/a/69067/1767754 I know

1) Static members in Python are not the same Static members in C++

2) Only newly created instances will have the latest Value synced Value of the static Variable

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

So what is a usual way of sharing member variables between class instances? What about creating a Global Class that holds the shared Data? like that:

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

test = Test()
test.setVar(3)
print Globals.var
Community
  • 1
  • 1
user1767754
  • 23,311
  • 18
  • 141
  • 164
  • 1
    Can't reproduce that, it always outputs the class' value. Also, static variables behave exactly like in C++, but don't forget that adding properties to objects can happen dynamically and lookup will first look in the instance and then in the class... – Ulrich Eckhardt Oct 05 '15 at 04:27
  • However, I got 5 in the last output.. – hsfzxjy Oct 05 '15 at 04:30
  • Sorry i've created bullshit, i am quickly checking... – user1767754 Oct 05 '15 at 04:37

1 Answers1

3

Only newly created instances will have the latest Value synced Value of the static Variable

Not true. Perhaps you are confusing the behavior of:

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)

Output:

a 3
b 5
a 5

with the behavior of

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

In the second case, var is not only a static member of T, it is also a member of instance a.

R Sahu
  • 204,454
  • 14
  • 159
  • 270