Thank you for supporting Python learners, who got stuck! I'd like to create an array of objects and encountered some weird behaviour of Python. Here's the code:
class Box:
def __init__(self, row, col):
self.row = row
self.col = col
def __str__(self):
return f"this is box[{self.row}][{self.col}]"
# instancing the boxes
boxes = 3*[3*[None]]
for i in range(2):
for j in range(2):
boxes[i][j] = Box(i, j)
print(boxes[i][j])
print()
print(boxes[0][0])
And this is the output:
this is box[0][0]
this is box[0][1]
this is box[1][0]
this is box[1][1]
this is box[1][0]
The last print statement shows the problem: When you call boxes[0][0], you get boxes[1][0]. Python seem to stick with the last instanced row index. This problem does not occur with list of objects, only with arrays. I suspect a limitation in Python (I'm using 3.8.5). I searched the web, but found nothing. What do you think is the problem here? How would you create this array of objects? Thank you very much for your help!