如何在Python中的不同模块中使用全局变量 [英] how to have global variables among different modules in Python
本文介绍了如何在Python中的不同模块中使用全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我调查了Python中全局变量的作用域限于模块。但是我需要在不同模块中成为全球化的范围。有这样的事吗?我玩过 __ builtin __
但没有运气。
感谢您!
在模块 foo
:
joe = 5
在模块 bar
中:
from foo import joe
print joe
请注意,这是不过建议。通过使用函数隐藏对模块变量的访问会更好。
I investigated that scope of global variables in python is limited to the module. But I need the scope to be global among different modules. Is there such a thing? I played around __builtin__
but no luck.
thanks in advance!
解决方案
You can access global variables from other modules by importing them explicitly.
In module foo
:
joe = 5
In module bar
:
from foo import joe
print joe
Note that this isn't recommended, though. It's much better to hide access to a module's variables by using functions.
这篇关于如何在Python中的不同模块中使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文