xiazh

在python中,全局变量一般有两种使用方式:

第一种:是在一个单独的模块中定义好,然后在需要使用的全局模块中将定义的全局变量模块导入。

第二种:直接在当前的模块中定义好,然后直接在本模块中通过global声明,然后使用

具体的方法如下所示:

第一种:

SOLR_URL=\'http://solr.org\'
def tt():
    global SOLR_URL
    SOLR_URL=SOLR_URL+\'#aa\'

if __name__==\'__main__\':
    tt()
    print SOLR_URL

#输出:
http://solr.org#aa

PS:在此种用法中,如果我们在函数tt中不使用global 声明全局变量SOLR_URL,其实也可以使用,但是此时应该是作为一个内部变量使用,由于没有初始值,因此报错

     Python查找变量是顺序是:先局部变量,再全局变量

SOLR_URL=\'http://solr.org\'
def tt():
    #global SOLR_URL
    SOLR_URL=SOLR_URL+\'#aa\'

if __name__==\'__main__\':
    tt()
    print SOLR_URL

#输出:
    SOLR_URL=SOLR_URL+\'#aa\'
UnboundLocalError: local variable \'SOLR_URL\' referenced before assignment

 

第二种:

global_list.py

GLOBAL_A=\'hello\'
GLOBAL_B=\'world\'

test.py

import global_list
def tt():
    print global_list.GLOBAL_A

if __name__==\'__main__\':
    tt()

#输出:
hello

 

 

分类:

技术点:

相关文章:

  • 2021-11-05
  • 2022-03-06
  • 2021-11-15
  • 2021-11-05
  • 2022-12-23
  • 2021-11-05
  • 2021-11-05
  • 2021-11-05
猜你喜欢
  • 2021-11-15
  • 2021-11-15
  • 2022-12-23
  • 2021-11-15
  • 2021-11-15
相关资源
相似解决方案