只是对 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代码
#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
这里我不明白“function reset()”执行后,全局值的结果在cli.py中没有改变(cli 2:150847672 1),但是回到gl.py,全局值确实改变了!!