为什么重置python全局值不生效 [英] Why reset python global value doesn't take effect

查看:79
本文介绍了为什么重置python全局值不生效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是对Python的全局值感到困惑,这里有两段代码

Just confused about global value in Python, here are two piece of code

#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,全球价值确实发生了变化!

Here I don't understand after "function reset()" execution, the result of global value doesn't change in cli.py(cli 2: 150847672 1), but back to gl.py, global value does change!!

推荐答案

此处缺少两个概念

  • 全局变量是模块的全局变量,而不是跨模块的全局变量

引用: 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

如果您需要在模块之间共享全局变量,请参考

If you need to share Global variables across modules refer How do I share global variables across modules?

这篇关于为什么重置python全局值不生效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆