【问题标题】:Python class is changing global variable without declaring it globalPython 类正在更改全局变量而不将其声明为全局变量
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 所以可以更改全局列表的元素而不将列表本身声明为全局?很高兴知道,谢谢。
  • 是的,对于列表和字典,或任何其他可变对象。
猜你喜欢
  • 1970-01-01
  • 2017-06-02
  • 2021-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-25
  • 1970-01-01
相关资源
最近更新 更多