首页 > 解决方案 > Python对象数组的奇怪行为

问题描述

感谢各位Python学习者的支持,被卡住了!我想创建一个对象数组,但遇到了 Python 的一些奇怪行为。这是代码:

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])

这是输出:

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]

最后一个 print 语句显示了问题:当你调用 box[0][0] 时,你得到了 box[1][0]。Python 似乎坚持使用最后一个实例行索引。对象列表不会出现此问题,仅数组会出现此问题。我怀疑 Python 存在限制(我使用的是 3.8.5)。我在网上搜索,但一无所获。你认为这里的问题是什么?你将如何创建这个对象数组?非常感谢您的帮助!

标签: pythonarraysoopobject

解决方案


推荐阅读