首页 > 解决方案 > Python:当变量被类方法调用时,对象变量存在“NameError”

问题描述

我正在制作一个带有网格的程序,我需要一个二维数组。在Grid对象的构造函数中,我初始化了 2 个变量,一个tuple保存坐标的变量,以及一个二维对象数组。tuple(Named, selected)作品完美。数组(命名gridArray)没有按预期工作。

当我在selectCell调用该方法时运行程序时出现错误 "NameError: name 'gridArray' is not defined"

为了测试它,我变成gridArray了一个简单的 int,程序给出了同样的错误。我还用以下方法调用它:

Grid.gridArray 这给出了网格数组没有名为的变量的错误gridArray

self.gridArray 该错误基本上说self未定义。

代码:

class Grid:
    def _init_(self):
        gridArray = 5      #[[cell.Cell() for j in range(9)] for i in range(9)]
        selected = (-1,-1)

    def selectCell(x):
        selected = (int(x[0]/const.CELLSIZE),int(x[1]/const.CELLSIZE))
        print(selected)
        print(gridArray)

print(gridArray)应该只打印 5,它只是一个NameError

标签: pythonpython-3.x

解决方案


您需要引用特定实例gridArray的属性。这通常用 来完成,并且是区分类变量、实例变量和局部变量所必需的:self

class Grid:

    # Class variables are defined here. All instances of the class share references to them.

    def __init__(self):
        # Anything prefixed with "self" is an instance variable. There will be one for each instance of Grid.
        # Anything without is a local variable. There will be one for each time the function is called.
        self.gridArray = 5
        self.selected = (-1, -1)

    def selectCell(self, x):
        self.selected = (int(x[0] / const.CELLSIZE),int(x[1] / const.CELLSIZE))
        print(self.selected)
        print(self.gridArray)

推荐阅读