为什么导入函数定义的全局变量不改变?

Why don't global variables defined by imported functions change?

我在文件中有一个函数:

global_value = 100    #defualt
def function(new_value):
    global global_value
    print(global_value,new_value)
    global_value = new_value

function() 接收一个值,将其与 global_value 进行比较,然后将 global_value 设置为 new_value。

我没有在文件中使用这个函数,而是导入它。

(文件 2:)

from file import *
value = input("enter value")
function(value)
print(global_value)

该函数工作正常,但最后 global_value 显示为等于 100(默认值),而不是输入。 我该怎么做才能在 file2 中也进行 global_value 更改?

谢谢。

Python 中的全局变量并不是真正的全局变量;它们仅限于特定模块。

执行from file import *后,你有两个个变量; file.global_variable,这是 file.function 更新的那个,当前模块中的新 global_variable 使用 初始化 的原始值 file.global_variable,但从未被 function.

更新

每个函数都包含对定义 函数的全局作用域的引用。在 Python 2 中是 file.function.func_globals;在 Python 3 中 tmp.function.__globals__。这是查找其任何 "global" 变量的范围,而不是 调用 .

函数的范围

将普通 import file 添加到您的第二个文件,然后 运行 print(global_variable, file.global_variable) 以查看差异。