我似乎无法理解这里发生了什么:
class testclass:
def __init__(self):
print "new instance"
myList=[]
if __name__ == "__main__":
inst1=testclass()
inst1.myList.append("wrong")
inst2=testclass()
inst2.myList.append("behaviour")
print "I get the",inst2.myList
输出是:
new instance
new instance
I get the ['wrong', 'behaviour']
我原以为 inst1 中的列表对 inst2 中的列表一无所知,但不知何故它看起来像 myList 的范围超越类的实例化。 我觉得这非常令人不安和困惑,还是我在这里遗漏了什么?
谢谢!
最佳答案
您定义 myList
的方式是一个类属性。
您寻找的行为是对象属性之一:
class testclass:
def __init__(self):
print "new instance"
self.myList = []
让我们试试看:
>>> t1 = testclass()
new instance
>>> t2 = testclass()
new instance
>>> t1.myList.append(1)
>>> t2.myList.append(2)
>>> t1.myList
[1]
>>> t2.myList
[2]
如果您对类属性感兴趣,请查看 Class documentation .由于 Python 中的类也是对象,就像(几乎)Python 中的所有东西一样,它们可以有自己的属性。
关于python - 令人费解的作用域行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9394428/