我不明白下面的代码是如何工作的:
class Host:
name = None
fileList = []
def __init__(self, hostName):
self.name = hostName
def AddInfo(self,file):
self.fileList.append(file)
def Cleanup(self):
self.fileList = []
我创建了 2 个实例:
h1 = Host("hostName1")
h1.AddInfo("h1")
h1.Cleanup()
print h1.fileList, Host.fileList
h2 = Host("hostName2")
h2.AddInfo("h2")
print h2.fileList, Host.fileList
结果是:
h1.fileList = [], Host.fileList = ['h1']
h2.fileList = ['h1', 'h2'], Host.fileList = ['h1', 'h2']
为什么Host.fileList
值会改变 - 我只为实例分配了新值?为什么h2.fileList
有这样的价值 - 我在这里期待['h2']
?