好了,我花了一些時間來縮小這個問題,但它似乎蟒蛇是這樣做的一個目的。有人可以解釋爲什麼會發生這種情況,我能做些什麼來解決這個問題?Python模塊/類變量出血
文件: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")
輸出:
c1: foo:hello
c2: foo:hello
我最好的猜測是,由於library
有"__init__.py"
文件時,整個模塊像類對象一樣加載,現在它成爲持久對象的一部分..是這樣的情況?
由於這是類/實例變量的問題,並且與模塊無關,您是否可以修改問題標題? – 2009-04-24 10:04:22