我想知道在多脚本 python 项目中使用全局变量的最佳方法是什么。 我看过这个问题:Using global variables between files? - 虽然接受的答案有效,但解决方案似乎很笨拙。
请参阅下面的一组脚本。只有 main.py 被直接调用;其余均为进口。
首先,我在一个单独的文件中声明了我的全局变量:
#global_vars.py
my_string = "hello world"
main.py
使用自定义函数打印字符串的值,更改全局变量的值,然后打印新值
#main.py
import global_vars
import do_things_module
#Print the instantiated value of the global string
do_things_module.my_function()
#Change the global variable globally
global_vars.my_string = "goodbye"
#Print the new value of the global string
do_things_module.my_function()
do_things_module.py
包含我们的自定义打印函数,并直接从全局获取字符串
#do_things_module.py
import global_vars
def my_function():
print(global_vars.my_string)
必须继续引用 global_vars.my_string
而不仅仅是 my_string
以确保我总是读取/写入全局范围的变量似乎是冗长的而且不是很 ' python '。有更好/更简洁的方法吗?
最佳答案
如果您的目标是使用 my_string
而不是 global_vars.my_string
,您可以像这样导入模块:
from global_vars import *
您应该能够直接使用my_string
。
关于python - 在 Python 中的文件之间共享全局变量的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29794610/