Python类正在改变全局变量而不将其声明为全局变量

时间:2017-10-19 02:14:12

标签: python python-2.7 class global-variables

我在定义类中的函数时出错了,但它并没有改变代码在运行时的运行方式。

我所犯的错误是在使用实例变量时使用全局变量。

我打算写的是:

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)

我试图搜索这个但我只能找到关于想要在课堂上使用全局变量的人的帖子,我特别想尝试不这样做。

1 个答案:

答案 0 :(得分:0)

显然,您的代码之前已经创建了一个全局map_data变量,因此您显示的代码不会重新创建map_data变量,它只是修改现有变量的元素。现有变量是通过常规名称查找找到的,因此在这种情况下可以在全局上下文中找到它。