I am using the following code to create a list of objects. Each object has an attribute. Each time an object is created, an init
method is called to give it initial values, then new values are stored in the attribute.
class Obj():
a = []
def init(self):
for i in range(2):
self.a.insert(i, 0)
# Main
object_list = []
for i in range(5):
if i == 0:
aux = Obj()
aux.init()
else:
object_list.append(aux)
aux = Obj()
aux.init()
for j in range(2):
aux.a[j] = random.randint(0,50)
for i in range(len(object_list)):
print object_list[i].a
The expected output would be something like this, where the printed attributes are of length 2:
[21, 9]
[3, 43]
[1, 33]
[5, 12]
However I am getting something like:
[37, 15, 26, 9, 5, 16, 15, 16, 42, 31]
[37, 15, 26, 9, 5, 16, 15, 16, 42, 31]
[37, 15, 26, 9, 5, 16, 15, 16, 42, 31]
[37, 15, 26, 9, 5, 16, 15, 16, 42, 31]
I know that the problem is that the attribute a
of a newly created object points to the attribute a
of the previous one, thus I have only one a
attribute for all objects.
Why creating a new object does not mean creating a different attribute instead a reference to previous object's attributes?