I'm trying to add objects to a list but when I print elements of that list, I get the attributes of the last object.
import random
class Unit:
arr = []
def __init__(self):
self.arr.clear()
for i in range(2):
self.arr.append(random.randint(1, 100))
print("arr in Unit ", self.arr)
class SetOfUnits:
lst = []
def __init__(self):
self.lst.clear()
for i in range(3):
self.lst.append(Unit())
print("arr in SetOfUnits ", self.lst[i].arr)
p = SetOfUnits()
for i in range(3):
print(p.lst[i].arr)
I got this:
arr in Unit [17, 16]
arr in SetOfUnits [17, 16]
arr in Unit [98, 20]
arr in SetOfUnits [98, 20]
arr in Unit [16, 39]
arr in SetOfUnits [16, 39]
[16, 39]
[16, 39]
[16, 39]
The problem is with the last 3 lines. It looks like that objects p.lst[0], p.lst[1], p.lst[2] refer to the same object, not different ones. I would like to get:
[17, 16]
[98, 20]
[16, 39]
Could you help me to find out what am I doing wrong?