TypeError:“int”对象不可编辑…2D数组

2024-09-30 20:30:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图设置多维数组中包含的单元格的类属性Board.grid板. 我收到以下错误消息:

  File "newbs1.py", line 133, in get_and_set_board_item
    self.grid[x, y].set_cell(value, secondary)
  File "newbs1.py", line 129, in __getitem__
    return self.grid[x][y]
  File "newbs1.py", line 128, in __getitem__
    x, y = tup
  TypeError: 'int' object is not iterable

让x和y输入他们是如何从别人的帖子来的想法,它解决了他们的问题,但对我来说不起作用。在

^{pr2}$

Tags: inpyselfboard消息get属性错误
1条回答
网友
1楼 · 发布于 2024-09-30 20:30:41

我不确定其余代码的外观,但在线路:133self.grid[(x, y)].set_cell(value, secondary),看起来元组(x, y)不是一个单元格类型。在

也许可以试试:

class Board(object):
    def __init__(self):
        self.grid = []
        self.width = 10
        self.height = 10

    def __getitem__(self, tup):
        x, y = tup
        return self.grid[x][y]

    def get_and_set_board_item(self, x, y, value, secondary):
        print (x, y, value, secondary)
        # add this line #
        self.grid[x][y] = Cell() # set this to a cell type
        # ************* #
        self.grid[x][y].set_cell(value, secondary)


class Cell():
    def __init__(self):
        self.is_ship = False
        self.is_hidden = False
        self.ship_symbol = ""

    def set_cell(self, value, secondary):
        if secondary == None:
            self.is_hidden = value
        else:
            self.is_ship = value
            self.ship_symbol = secondary

相关问题 更多 >