请查看以下代码段:
class MyObj(object):
name = ""
def __init__(self, name):
self.name = name
v = [ {} ] * 2
def f(index):
v[index]['surface'] = MyObj('test')
v[index]['num'] = 3
if __name__ == '__main__':
f(0)
f(1)
v[0]['num'] = 4
print v[1]['num']
我期望得到的最后一行的输出是3
;但它打印出4
。所以它应该意味着始终在相同的参考地址创建新对象。
我该如何避免这种行为? (即如何让上面的代码打印4?)
答案 0 :(得分:5)
您需要创建两个dicts:
v = [ {},{} ]
或使用循环:
v = [ {} for _ in range(2)]
您正在创建对同一对象的两个引用。
In [2]: a = [{}] * 2
In [3]: id(a[0])
Out[3]: 140209195751176
In [4]: id(a[1])
Out[4]: 140209195751176
In [5]: a[0] is a[1]
Out[5]: True
In [6]: a = [{} for _ in range(2)]
In [7]: id(a[1])
Out[7]: 140209198435720
In [8]: id(a[0])
Out[8]: 140209213918728
In [9]: a[0] is a[1]
Out[9]: False