所以我正在阅读 Alex Martelli 对 other question 的回答...
"One example in which I may want initialization is when at package-load time I want to read in a bunch of data once and for all (from files, a DB, or the web, say) -- in which case it's much nicer to put that reading in a private function in the package's init.py rather than have a separate "initialization module" and redundantly import that module from every single real module in the package..."
不幸的是,当我尝试这个时:
foo/__init__.py
import tables as tb
global foo
foo = tb.openFile('foo.h5', etc._)
import bar
foo/bar/__init__.py
import tables as tb
global bar
bar = foo.createGroup('/', bar)
import MyFunction`
foo/bar/MyFunction.py
def MyFunction(*of foo and bar*):
'...'
>>> import foo
>>> OUTPUT= foo.bar.MyFunction.MyFunction(INPUT)
>>> bar = foo.createGroup('/', bar)
NameError: name 'foo' is not defined
如何定义全局变量而不将它们放入函数中(如 here 所示)?
最佳答案
全局变量不是全局的,因为 Python 代码的每一部分都看到相同的全局变量集。全局性实际上只是“模块范围”;模块中定义的所有变量和函数都已经是全局的,并且尽可能全局。
如果您想在另一个模块的全局变量中查看一个模块中定义的变量,唯一的方法是将第一个模块的名称导入到第二个模块中...IE:
# myModule.py
foo = "bar"
# yourModule.py
from myModule import foo
关于Python:我可以在包 __init__ 模块中设置全局变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13280822/