Okay, it took me a little while to narrow down this problem, but it appears python is doing this one purpose. Can someone explain why this is happening and what I can do to fix this?
File: library/testModule.py
class testClass:
myvars = dict()
def __getattr__(self, k):
if self.myvars.has_key(k):
return self.myvars[k]
def __setattr__(self, k, v):
self.myvars[k] = v
def __str__(self):
l = []
for k, v in self.myvars.iteritems():
l.append(str(k) + ":" + str(v))
return " - ".join(l)
test.py
from library import testModule
#I get the same result if I instantiate both classes one after another
c1 = testClass()
c1.foo = "hello"
c2 = testClass()
print("c1: " + str(c1) + "\n")
print("c2: " + str(c2) + "\n")
Output:
c1: foo:hello
c2: foo:hello
My best guess is that because library has an "__init__.py" file, the whole module is loaded like a class object and it’s now become part of a lasting object.. is this the case?
myvarsis a property of the class, not the instance. This means that when you insert an attribute intomyvarsfrom the instancec1, the attribute gets associated with the classtestClass, not the instancec1specifically. Sincec2is an instance of the same class, it also has the same attribute.You could get the behavior you want by writing this: