【发布时间】:2009-04-24 00:57:06
【问题描述】:
好的,我花了一点时间来缩小这个问题的范围,但似乎 python 正在做这个目的。有人可以解释为什么会发生这种情况以及我能做些什么来解决这个问题吗?
文件:库/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" 文件,所以整个模块像类对象一样被加载,现在它变成了持久对象的一部分。是这样吗?
【问题讨论】:
-
由于这是类/实例变量的问题,与模块无关,能否修改题名?