【问题标题】:Local variable '' referenced before assignment赋值前引用的局部变量 ''
【发布时间】:2018-01-12 09:05:51
【问题描述】:

我有一个关于我的方法错误的小问题(如在一个类中),我目前正在研究一个想要找出机器人可以做的最佳移动的 AI,但是当我想返回 bestMove 时,它​​告诉我的错误。

def computerMove(self, tile, newBoard, legalMoves, isOnCorner):
        legitMoves = self.getLegalMoves(self.board, tile)
        for x, y in legitMoves:
             if self.isOnCorner(x, y):
                 return [x, y]
        highestPoints = -1
        for x, y in legitMoves:
            computerBoard = self.getComputerBoard(self.newBoard)
            makeYourMove(computerBoard, tile, x, y)
            points = countPoints(computerBoard)[tile]
            if points > highestPoints:
                highestPoints = points
                bestMove = [x][y]
        return bestMove

但错误状态

UnboundLocalError:赋值前引用了局部变量“bestMove”

【问题讨论】:

  • 你必须在for循环之前给bestMove赋值,因为如果if条件为假,bestMove没有赋值,函数会返回None。跨度>
  • 检查我的更新! @ikreb

标签: python python-3.x


【解决方案1】:

看看这段代码:

for x, y in legitMoves:
    computerBoard = self.getComputerBoard(self.newBoard)
    makeYourMove(computerBoard, tile, x, y)
    points = countPoints(computerBoard)[tile]
    if points > highestPoints:
        highestPoints = points
        bestMove = [x][y]
return bestMove

如果没有legitMoves 或没有移动得分points > highestPoints(我认为这永远不会是这种情况,因为countPoints 很可能至少返回0)然后bestMove 将永远不会被定义,@ 987654327@ 应该是bestMove = [x, y]

尝试将bestMove = None 放在for 循环之前,然后在调用代码中处理None

【讨论】:

  • 我很明白你的意思,但它不起作用。检查我的更新!
  • 哦,我想我目前正在解决它,如果我需要更多帮助,我会回来的! ty
  • @PythonGirl 请仔细查看完整的回溯并尝试阅读其中的所有信息。如果这没有帮助,您可以在此处发布完整的回溯,或者在新问题中更好地发布。您没有在此处包含回溯的事实表明您认为它不相关,而它实际上是与错误最相关的信息。
猜你喜欢
  • 1970-01-01
  • 2013-08-02
  • 2011-11-06
  • 1970-01-01
相关资源
最近更新 更多