Python 的全局变量

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 的全局变量相关的知识,希望对你有一定的参考价值。

 

结论: Python 的全局变量只在本文件中生效。

定义全局变量的文件 G.py

 1 # define some global variable
 2 
 3 A = 1
 4 B = 2
 5 C = 3
 6 
 7 def fuck(a=0, b=0, c=0):
 8     global A, B, C
 9     A = a
10     B = b
11     C = c
12 
13 def fuck2():
14     global A, B, C
15     print In fuck2, A = %d, B = %d, C = %d % (A, B, C)

使用全局变量的文件 use_G.py

from G import *

def shit():
    global A, B, C
    print Before, A = %d, B = %d, C = %d % (A, B, C)
    fuck()
    fuck2()
    print After, A = %d, B = %d, C = %d % (A, B, C)

if __name__ == __main__:
    shit()

打印结果如下,

Before, A = 1, B = 2, C = 3
In fuck2, A = 0, B = 0, C = 0     # ===> 可见在同一文件中,全局变量的变化是可以传递的。
After, A = 1, B = 2, C = 3        # ===> 可见跨越文件,全局变量时不能传递的。
                     # 解决方法1:使用返回值带回。
   # 解决方法2:生产全局变量的脚本写中间文件,比如写一个 cPickle 文件,或者一个数据库文件,使用全局变量的脚本读这个中间文件

 

完。

 

以上是关于Python 的全局变量的主要内容,如果未能解决你的问题,请参考以下文章

python基础局部变量全局变量

R Shiny中是否存在全局变量?

Python 全局变量

Python20之全局变量和局部变量

Python 变量范围

PYTHON 函数局部变量和全局变量