python中多个文件的全局变量

时间:2016-03-11 09:52:34

标签: python global

我在包括Using global variables between files in Python?在内的不同论坛中进行了大量搜索,虽然有一些主题讨论全局变量和多个文件,但我无法找到问题的正确答案。我创建了三个虚拟代码来解释我的问题。

globalss.py

test_value = [0]

test.py

from globalss import *
def datagen():
  global test_value
  test_value = [100]
  print('test_value from datagen', test_value)
datagen()
def valchange(x):
  global test_value
  test_value = [x]
  print('test value in val change', test_value)
valchange(1000)

testing.py

from test import *
from globalss import *
print('test_value from testing', test_value)
valchange(22222)
print('test_value from testing', test_value)

testing.py是我作为 main 运行的文件。

output

test_value from datagen [100]
test value in val change [1000]
test_value from testing [0]
test value in val change [22222]
test_value from testing [0]

无论在test_value上应用何种操作,testing.py的值都为0。 所以基本上从我所理解的测试代码中,模块将在导入时获得全局变量的值。之后,无论其他文件中的变量发生什么,它都不会反映在该特定模块中。

我从其他页面找到的所有答案都在谈论在公共文件中初始化变量并将该文件导入不同的模块。正如我在示例中所示,将导入该值。但是一旦导入,之后在其他文件中所做的更改将填充在当前文件中。

我的问题是,有没有办法在不同的文件中共享全局变量,其中值的变化将反映在所有文件中。

0 个答案:

没有答案