在python中导入全局名称空间 [英] Importing global namespace in python
问题描述
假设我有以下文件:
a.py
glo_var = 0
def func():
global glo_var
glo_var = 5
print "A %d" % (glo_var)
b.py
from a import *
func()
print "B %d" % (glo_var)
如果我运行b.py,输出为:
If I ran b.py the output is:
A 5
B 0
我的问题是,如何导入全局名称空间,以便输出为
My question is, how to import the global namespace so the output will be
A 5
B 5
我需要从b.py中调用a.py模块中的函数,以免影响全局变量.
I need to call the function in the module a.py from b.py so it will affect the globals.
我不想使用常规的导入",而是以这种方式使用它,从导入*"
推荐答案
使用from ... import ...
从另一个模块复制引用.重新绑定原始值会导致它具有新的引用,从而永久断开a.glo_var
和b.glo_var
之间的链接.使用可变对象并对其进行突变,或者在需要更新值时重新导入a.glo_var
.
Using from ... import ...
copies the references from the other module. Rebinding the value in the original causes it to have a new reference, breaking the link between a.glo_var
and b.glo_var
permanently. Either use a mutable object and mutate it, or reimport a.glo_var
whenever you need the updated value.
这篇关于在python中导入全局名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!