Python global variable literacy

Python is not really global variables in Java and C ++, global variables are procedure-level, stand on their point of view, the python is no global variables in python's point of view, there is a global variable, python provides global keyword you can modify global variables, global variables in python just for the current python file / module defined, python file is a module, independent namespaces, variables defined in this module will only belong to the namespace, so, python no true global variables, global variables only at the file level.

So Python global variables is a relative term

Examples:
test.py

a = 1

t1.py

import sys
import test # 导入test模块

a = 1 # 声明一个变量

def func1():
    global a # 引用当前命名空间的全局变量
    a += 1

def func2():
    test.a += 1  # 引用test模块命名空间的变量

def func3():
    # print(sys.modules) # 记录当前文件导入的所有模块
    module = sys.modules['test'] # 二次引用已导入的test模块
    module.a += 1       # 引用test模块命名空间的变量

func1()
func2()
func3()

print(a)        # 结果:2
print(test.a)   # 结果:3

Guess you like

Origin blog.51cto.com/12643266/2429895