版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/infoworld/article/details/84669484
场景
1.在做python
开发时, 有时候会用到全局变量, 比如某个配置需要影响到程序的生命周期, 或者多线程程序里, 需要判断某个变量是True
, 从而知道需要停止任务执行.
2.C++
的全局变量只需要在头文件里声明一个extern int gTime;
即可, 之后在.cpp
里定义变量即可. 之后其他文件如果需要用到这个变量, 就包含这个头文件即可. 如果需要跨动态库使用的话, 还需要单独编译一个带extern int GetTime()
的动态库才行, 之后其他库只需要调用这个导出函数GetTime
的动态库即可.
3.Java
是基于类加载机制的, 同一个类可以通过不同的代理多次加载, 所以没有全局变量.
说明
1.python
全局变量是基于模块的, 因为每个模块只有一个实例. 在声明全局变量时, 只需要在需要全局使用的.py
文件里A.py
声明一个全局变量即可.x = False
,之后导入import A
, 并对A.x = True
赋值。按照docs.python.org
的说明, 使用的时候都不需要声明global x
, 只需要全模块路径即可.
例子
文件的层次关系:
1.src/gui/utility.py
gIsStop = False
2.src/gui/window/test_global2.py
import src.gui.utility
def GetGlobal():
print (__file__)
return src.gui.utility.gIsStop
def SetGlobal(value):
src.gui.utility.gIsStop = value
3.src/test_global1.py
import src.gui.utility
import importlib
from src.gui import utility
import _thread
import time
def worker():
test_global2 = importlib.import_module('src.gui.window.test_global2')
print(test_global2.GetGlobal())
test_global2.SetGlobal(False)
print(__file__)
print(src.gui.utility.gIsStop)
if __name__ == "__main__":
print (__file__,)
print (src.gui.utility.gIsStop)
utility.gIsStop = True
_thread.start_new_thread(worker, ())
time.sleep(10)
输出:
E:/Project/Sample/test-python/src/test_global1.py
False
E:\Project\Sample\test-python\src\gui\window\test_global2.py
True
E:/Project/Sample/test-python/src/test_global1.py
False
参考
How do I share global variables across modules?
visibility-of-global-variables-in-imported-modules
python-dynamic-import-how-to-import-from-module-name-from-variable
globals()
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).