python - 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
解决方案
您需要引用特定实例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)
推荐阅读
- arrays - 我们如何在数组中找到唯一的对?
- php - 我不希望页面在 php 执行后刷新
- windows - 为什么 XCOPY /W 和 REPLACE /W 会为他们的单字符提示使用所有重定向的文本数据?
- ios - iOS 应用程序能否以编程方式将 Apple Watch 置于飞行模式?
- java - 将 Erlang 与 Java 库链接
- ajax - ajax调用后如何刷新模板
- javascript - 搜索和更新嵌套在 Javascript 数组中的对象的属性
- r - 将类型分配给 xyplot
- c++ - 识别来自 Windows 10 应用程序的 Toast 通知区域
- javascript - 在 Materialise 中添加新幻灯片