为什么从另一个模块读取时全局值不会改变?
Why global value doesn't change when reading from another module?
我有三个文件:
globals.py:
value = None
reader.py:
from globals import *
def read_global():
print(value)
changer.py:
from globals import *
from reader import *
def change_global():
global value
value = 1
change_global()
read_global()
我希望对“read_global”的调用会打印 1,但会打印值 None。
为什么会这样?为什么“change_global”中设置的新值不打印?
将您的导入更改为
changer.py:
from reader import *
import globals as g
def change_global():
g.value = 1
change_global()
read_global()
print(g.value)
reader.py:
import globals as g
def read_global():
print(g.value)
globals.py:
value = None
我认为当您在 change_global 函数中调用值时,您并不是在调用您在 global.py
中声明的全局变量,而是在函数内部创建新的局部变量,因此当您将导入别名设置为g
将确保你 call/set 是正确的(变量)
我一直在阅读 Python 文档中有关模块的内容,它指出:
Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname.
这意味着全局符号 table 不在模块之间共享。
我有三个文件:
globals.py:
value = None
reader.py:
from globals import *
def read_global():
print(value)
changer.py:
from globals import *
from reader import *
def change_global():
global value
value = 1
change_global()
read_global()
我希望对“read_global”的调用会打印 1,但会打印值 None。
为什么会这样?为什么“change_global”中设置的新值不打印?
将您的导入更改为
changer.py:
from reader import *
import globals as g
def change_global():
g.value = 1
change_global()
read_global()
print(g.value)
reader.py:
import globals as g
def read_global():
print(g.value)
globals.py:
value = None
我认为当您在 change_global 函数中调用值时,您并不是在调用您在 global.py
中声明的全局变量,而是在函数内部创建新的局部变量,因此当您将导入别名设置为g
将确保你 call/set 是正确的(变量)
我一直在阅读 Python 文档中有关模块的内容,它指出:
Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname.
这意味着全局符号 table 不在模块之间共享。