Tags : Ajax  apache  awk  besttrace  bootstrap  CDN  Django  git 

常见问题

Python:全局变量的使用

stevezhou      2014.08.07   


Python中全局变量的两种使用方法:

1、声明法

在文件开头声明全局变量variable,

在具体函数中使用该变量时,需要事先声明 global variable,否则系统将该变量视为局部变量。

ONSTANT = 0  (将全局变量大写便于识别)
      
def modifyConstant() :
        global CONSTANT
        print CONSTANT
        CONSTANT += 1
        return
      
if __name__ == '__main__' :
        modifyConstant()
        print CONSTANT

2、模块法(推荐)

把全局变量定义在一个单独的模块中:

#gl.py
gl_1 = 'hello'
gl_2 = 'world'

在其它模块中使用

#a.py
import gl
   
def hello_world()
    print gl.gl_1, gl.gl_2
   
#b.py
import gl
   
def fun1()
    gl.gl_1 = 'Hello'
    gl.gl_2 = 'World'

第二种方法,适用于不同文件之间的变量共享,而且一定程度上避免了开头所说的全局变量的弊端,推荐!

 

python名字、作用域名及名字空间 (PDF文件来自:http://wiki.woodpecker.org.cn/moin/BPUG/2007-09-01?action=AttachFile&do=get&target=py-names-robertchen.pdf)



标签 :  全局变量 下一篇