【发布时间】:2017-10-19 02:14:12
【问题描述】:
我在类中定义函数时出错,但它不会改变代码在运行时的操作方式。
当我的意思是使用实例变量时,我犯的错误是使用全局变量。
我想写的是:
self._map_data[screen_pos_layer][y][x] = selected_material
相反,我写道:
map_data[screen_pos_layer][y][x] = selected_material
但是,无论是实例化变量还是全局变量,预期的功能(更改 LED 的颜色)都不会改变。实际将颜色写入 LED 的函数属于不同的类。
我认为只有在我包含 global <variable> 时才会发生这种情况?我对 Python 的经验很少,但我确信这是真的。
class Tools(object):
def __init__(self, _map_data):
self._map_data = _map_data
def paint(self, event):
if selected_tool == select_paint and selected_color != -1:
for j in range(cursor_size_y):
for i in range(cursor_size_x):
y = screen_pos_y + cursor_pos_y + j
x = screen_pos_x + cursor_pos_x + i
map_data[screen_pos_layer][y][x] = selected_material
else:
return
moveCursor(event)
tools = Tools(map_data)
# this is a Tkinter object
window.bind_all("<Control-Up>", tools.paint)
我尝试搜索此内容,但我只能找到有关人们希望在课程中使用全局变量的帖子,我特别不想这样做。
【问题讨论】:
-
你完全误会了。在 Python 中,如果在本地范围内找不到名称,它会检查全局变量。
标签: python python-2.7 class global-variables