python 多个文件共享数据/变量

python的每个文件相当于一个module,每个module有自己的命名空间(也可以说是作用域),在多个文件中共享变量可以使用import来实现。
import有个缓存机制,即在某一次python解释器运行时,模块只导入一次、代码只执行一次,若有重复的导入操作,则会从缓存中直接读取其中的变量,举例如下:

# config.py
import time
a = time.time()
# config_test.py
import config
print 'config_test:',
print config.a
import config
import config_test
print 'another_test:',
print config.a,
# run_test.py
import config_test
import another_test

运行run_test.py:

O:\lab\PycharmProjects\>python run_test.py
config_test: 1517482042.35
another_test: 1517482042.35

可见在一次python运行时,config_test.py和another_test.py共享了config.py中的变量a

参考:
http://blog.csdn.net/tuxl_c_s_d_n/article/details/45462139
https://docs.python.org/3/reference/import.html

猜你喜欢

转载自blog.csdn.net/u010895119/article/details/79232098