''object'在2d python列表中无法编写脚本

问题描述 投票:0回答:1

Message ='SodokuGame'对象不可下标源= C:\ Users \ PC \ Desktop \ python \ Soduku \ Soduku \ Soduku.pyStackTrace:文件“ C:\ Users \ PC \ Desktop \ python \ Soduku \ Soduku \ Soduku.py”,第31行,在fillArray如果currentArray [x] [y] .value == 0:

文件“ C:\ Users \ PC \ Desktop \ python \ Soduku \ Soduku \ Soduku.py”,第110行,在init中game.fillArray(game.matrix,0,0,game.newPool)文件“ C:\ Users \ PC \ Desktop \ python \ Soduku \ Soduku \ Soduku.py”,第113行,在Run()

我正在尝试自己的项目,遇到了一个问题。首先,我有我的手机班。我的目标是测试Cell中的数据并根据结果运行代码,但在运行时我遇到上述错误。

class Cell:
value = 0
def __getitem__(self):
    return self.value
def __setitem__(newVal, self):
    self.value = newVal

这是我定义并尝试添加列表的方式

class SodokuGame:


matrix = []
for i in range(9):
    arr = []
    for j in range(9):
        arr.append(Cell())
    matrix.append(arr)


def fillArray(currentArray, x, y, pool, self):


    if currentArray[x][y].value == 0:
        print("fillArray loop") #unimportant context code from here on
        poolNum = randint(0, pool.length)
        if testNumber(pool[poolNum]):
            currentArray[x][y]= pool.pop(pool[poolNum])
            print(poolNum)

我的第一个假设是数组被错误地填充以使if语句失败,但这不是问题。我相信问题是在

if currentArray[x][y].value == 0:

某种程度上,即使我实例化了(x,y)处的所有节点,它仍然给我一个错误,好像我正在将SodukuGame对象与0进行比较。

最初的称呼是:

class Run:
def __init__(self):
    print("Run")
    game = SodokuGame()
    game.printGrid()
    game.fillArray(game.matrix, 0, 0, game.newPool)
    game.printGrid()
Run()

注:我认为这与问题无关,但是此函数的目的是检查当前单元格是否为空(= 0),如果不是,它将尝试填充该单元格并递归运行该函数再次移动到一个单元格上,直到结构填满。

我已经尝试在Cell类中实现方法来解决此问题,包括添加__getitem__函数,本机getInfo函数,甚至尝试使用isZero布尔函数,但所有这些导致同样的错误。这不是为了功课。

python nested-lists
1个回答
0
投票

欢迎贾斯汀。这里有一些问题,但是第一个问题是您没有使用self启动实例方法。 Python仍将那些变量像self一样对待,这就是为什么出现错误“ SodokuGame无法下标”的原因。它不是对您要传递的矩阵进行下标;它用SodokuGame类本身的实例化对象下标。

这是SodokuGame类的fillArray方法应该是的样子

class SodokuGame:
    def fillArray(self, currentArray, x, y, pool):
      if currentArray[x][y].value == 0:
        # do stuff

[您会注意到我将self放在参数列表的前面,这是您始终需要做的。 Python不会监听self的放置位置,因为从技术上讲,您可以随意命名它(您不应该,但是可以)。它始终始终是实例方法中的第一个参数。

此后,您将遇到Cell问题。您正在实现__getitem__,但是Cell没有要下标的数组。如果您确实想对它进行下标,但由于某种原因总是返回相同的值,则需要正确实现该方法(__setitem__也是如此):

class Cell:
    value = 0
    def __getitem__(self, item):
        return self.value
    def __setitem__(self, item, value):
        self.value = value

如果您实际上不想下标Cell,即您不想做

c = Cell()
c[247321] = 2
# 247321 can literally be anything; 'turkey', 12, 32.1, etc.
# that is what item is in the __getitem__ and __setitem__ methods, and
# you're not using that argument that in the implementations

您可能不应该使用__getitem__,而应该执行以下操作:

class Cell:
    def get_value(self):
        return self.value
    def set_value(self, value):
        self.value = value

但是您也可以使用.value直接访问属性的方法。

© www.soinside.com 2019 - 2024. All rights reserved.