I am building a project that requires the data to be shared globally. I built a class GlobalDataBase to handle these data, which is like the way in How do I avoid having class data shared among instances? and https://docs.python.org/2/tutorial/classes.html . However, I found something a little bit weird to me. My code is as follows:
class GlobalDataBase:
a = []
def copy_to_a(self, value):
self.a = value
def assign_to_a(self, value):
for idx in range(0, len(value)):
self.a.append(value[idx])
def test_copy():
gb1 = GlobalDataBase()
gb1.copy_to_a([1,2])
print gb1.a
gb2 = GlobalDataBase()
print gb2.a
def test_assign():
gb1 = GlobalDataBase()
gb1.assign_to_a([1,2])
print gb1.a
gb2 = GlobalDataBase()
print gb2.a
The output of test_copy
is
[1,2]
[]
The output of test_assign
is
[1,2]
[1,2]
The result of the second method is what I was expecting. But I could not understand why the first method doesn't work. Could anyone explain the difference between these two methods?