只是困惑在Python全球价值,这里有两个代码段
#gl.py
import cli
a = 1
print "gl 1: %d %d" % (id(a), a)
def reset():
global a
a = 7
print "reset 1: %d %d" % (id(a), a)
if __name__ == '__main__':
cli.handler(reset)
print "gl 2: %d %d" % (id(a), a)
命令行代码
#cli.py
def handler(func):
from gl import a
print "cli 1: %d %d" % (id(a), a)
func()
print "cli 2: %d %d" % (id(a), a)
执行的结果是
$ python gl.py
gl 1: 150847672 1
gl 1: 150847672 1
cli 1: 150847672 1
reset 1: 150847600 7
cli 2: 150847672 1 #Why value doesn't change
gl 2: 150847600 7
在这里,我不“功能复位()”后明白的执行,全球价值的结果不会改变cli.py(CLI 2:150847672 1),但回到gl.py,全球价值的确改变了!
两个概念是缺少在这里
请参阅: http://legacy.python.org/doc/essays/ppt/hp-training/sld036.htm
请参阅: http://docs.python.org/release/2.4/ref/global.html
请参阅: https://stackoverflow.com/a/3338357/977038
如果您需要跨模块是指共享全局变量如何跨模块共享的全局变量?
你gl
模块导入两次为两个不同的命名空间
试试这个:
import sys
print sys.modules['__main__'].a
print sys.modules['gl'].a
您在CLI导入GL实际上是模块对象的副本。 如果我们改变这样的代码:
#gl.py
import cli
import sys
a = 1
print "gl 1: %d %d" % (id(a), a)
print "gl id on import: {0}".format(id(sys.modules[__name__]))
def reset():
global a
a = 7
print "gl id in reset: {0}".format(id(sys.modules[__name__]))
print "reset 1: %d %d" % (id(a), a)
def printa():
print "gl: %d %d" % (id(a), a)
if __name__ == '__main__':
cli.handler(reset)
print "gl id in main: {0}".format(id(sys.modules[__name__]))
print "gl 2: %d %d" % (id(a), a)
和
#cli.py
def handler(func):
#from gl import a
import gl
print "gl id in cli: {0}".format(id(gl))
print "cli 1: %d %d" % (id(gl.a), gl.a)
func()
print "cli 2: %d %d" % (id(gl.a), gl.a)
gl.reset()
print "cli 3: %d %d" % (id(gl.a), gl.a)
我们得到:
gl 1: 19056568 1
gl id on import: 140075849968728
gl 1: 19056568 1
gl id on import: 20004096
gl id in cli: 20004096
cli 1: 19056568 1
gl id in reset: 140075849968728
reset 1: 19056424 7
cli 2: 19056568 1
gl id in reset: 20004096
reset 1: 19056424 7
cli 3: 19056424 7
gl id in main: 140075849968728
gl 2: 19056424 7
所以,当我们运行复位,我们改变了参考
a -> 19056568
至
a -> 19056424
但只有在一个GL副本。 到旧参考另一个(一个在CLI)成立。 如果我们从CLI中运行gl.reset(),我们对副本的修改参考,并获得CLI预期的变化。