对于A类,为什么在对象和对象b之间共享aMap成员变量?
>>> class A:
... aMap = {}
>>> a = A()
>>> a.aMap["hello"] = 1
>>> b = A()
>>> b.aMap["world"] = 2
>>> c = []
>>> c.append(a)
>>> c.append(b)
>>> for i in c:
... for j in i.aMap.items():
... print j
('world', 2)
('hello', 1)
('world', 2)
('hello', 1)
Run Code Online (Sandbox Code Playgroud)
因为您将其定义为类属性,而不是实例属性.
如果您希望将其作为实例属性并且不在实例之间共享,则必须按如下方式对其进行定义:
class A(object):
def __init__(self):
self.aMap = {}
Run Code Online (Sandbox Code Playgroud)