Creating separate objects in a function
Take a look at the following piece of code:
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']
What I was expecting to get as the output of the last line is 3
; however it outputs 4
. Therefore, this should mean that a new object is always created at the same reference address.
How can I avoid this behavior? (i.e. how can I make the above code 4 prints?)
+3
Vito gentile
source
to share
1 answer
You need to create two dicts:
v = [ {},{} ]
Or use a loop:
v = [ {} for _ in range(2)]
You are creating two references to the same object.
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
+5
Padraic cunningham
source
to share