简体   繁体   English

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

[英]Python class is changing global variable without declaring it global

I made an error while defining a function within a class, yet it doesn't change how the code operates during runtime. 在类中定义函数时出错,但它不会更改代码在运行时的操作方式。

The error I made was using a global variable when I mean to use an instanced variable. 当我打算使用实例变量时,我犯的错误是使用全局变量。

What I meant to write was: 我的意思是:

self._map_data[screen_pos_layer][y][x] = selected_material

Instead, I wrote: 相反,我写道:

map_data[screen_pos_layer][y][x] = selected_material

However, the intended functionality (change the color of an LED) doesn't change, no matter if it's the instanced variable or the global variable. 但是,无论是实例变量还是全局变量,预期的功能(更改LED的颜色)都不会改变。 The function that actually writes the color into the LED is in a different class. 将颜色实际写入LED的功能属于另一类。

I thought that could only happen if I include global <variable> ? 我以为只有在包含global <variable>才会发生这种情况? I have very little experience with Python but I'm sure this was true. 我对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)

I tried searching for this but I could only find posts about people wanting to use a global variable in a class, I specifically am trying not to. 我尝试搜索此内容,但是我只能找到有关想要在类中使用全局变量的人的帖子,我特别想不这样做。

Evidently your code has previously created a global map_data variable, so the code you're showing is not re-creating the map_data variable, it is only modifying an element of the existing variable. 显然,您的代码先前已创建了全局map_data变量,因此您显示的代码不是在重新创建map_data变量,而只是在修改现有变量的元素。 The existing variable is found via regular name lookup, and so in this case it is found in the global context. 现有变量是通过常规名称查找找到的,因此在这种情况下,它是在全局上下文中找到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM