python - 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)。我在网上搜索,但一无所获。你认为这里的问题是什么?你将如何创建这个对象数组?非常感谢您的帮助!
解决方案
推荐阅读
- c++ - 为什么调试时没有显示控制台窗口
- angular - 按过滤器角度比较 2 个数组
- reactjs - 尝试将更新的状态传递给组件时如何修复 mapStateToProps 未定义?
- laravel - Laravel 背包中的关系 - 不确定我是否理解
- c++ - 没有连续 1 的位串,使用自顶向下 DP
- python - MacOS Catalina,pip 已安装包但 python 找不到它们?
- wordpress - 如何在 WordPress Post 中上传 Web 记录 Base64 Wave 音频文件(前端形式)
- html - 无法拖放任何链接到如果某些链接已经粘贴到前
- java - 休眠不设置外键
- c# - 如果您不需要强制转换,并且需要检查对象的最具体(运行时)类型,哪个更快?.GetType() & typeof(),还是运算符?