Python:当一个对象变量被一个类方法调用时,存在一个“NameError”

2024-04-19 23:38:34 发布

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

我正在做一个有网格的程序,我需要一个二维数组。在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


Tags: 对象self程序网格def错误数组grid
2条回答

您需要引用特定实例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)

类中的每个函数都需要解析self变量,以便在创建类时引用在类实例中定义的其他变量。现在,gridArray是__init__函数中的局部变量。你可以在这里阅读更多关于类的信息https://docs.python.org/3.7/tutorial/classes.html#class-objects

您应该将gridArray定义为self.gridArray,以便在类中的其他地方使用它。一定要在属于这样一个类的每个函数中分析self变量:def selectCell(self, x):一般格式是def <funcname>(self, *args): <code>。你知道吗

另外,__init__函数前后应该有2个下划线。你知道吗

相关问题 更多 >