不,你错了,两者都有key:5
:
In [56]: class Test1:
....: x=set()
....: y={}
....:
In [57]: hamster=Test1()
In [58]: chinchilla=Test1()
In [59]: hamster.x.add('hi') # now both sets in both instances have 'hi'
In [60]: hamster.y['key']=5
In [62]: hamster.x,chinchilla.x
Out[62]: (set(['hi']), set(['hi']))
In [63]: hamster.y,chinchilla.y
Out[63]: ({'key': 5}, {'key': 5})
实际上,在您的代码中,您不是在更改实例变量,而是在更改类变量:
In [65]: Test1.x
Out[65]: set(['hi'])
In [66]: Test1.y
Out[66]: {'key': 5}
你需要在这里使用实例变量:
In [71]: class Test1():
def __init__(self):
self.x=set()
self.y={}
....:
....:
In [75]: hamster=Test1()
In [76]: chinchilla=Test1()
In [77]: hamster.x.add('hi')
In [78]: chinchilla.x.add('bye')
In [79]: hamster.x
Out[79]: set(['hi'])
In [81]: chinchilla.x
Out[81]: set(['bye'])
In [82]: hamster.y['key']=5
In [83]: hamster.y,chinchilla.y
Out[83]: ({'key': 5}, {})