python引用变量的顺序:
当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量 。
global
# 定义了一个全局变量,(可以省略global关键字)
gcount = 0
def global_test():
#如果在函数中声明 gcount 是全局变量,即可对其进行修改。
global gcount
gcount+=1
print(gcount)
#2!!!, 在局部如果不声明全局变量,并且不修改全局变量。则可以正常使用全局变量:
gcount = 0
def global_test():
print(gcount)
# 如果在局部不修改全局变量,程序正确输出 0
nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
示例
def scope_test():
def do_local():
spam = "local spam" #此函数定义了另外的一个spam字符串变量,并且生命周期只在此函数内。此处的spam和外层的spam是两个变量,如果写出spam = spam + “local spam” 会报错
def do_nonlocal():
nonlocal spam #使用外层的spam变量
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignmane:", spam)
do_nonlocal()
print("After nonlocal assignment:",spam)
do_global()
print("After global assignment:",spam)
scope_test()
print("In global scope:",spam)
"""
After local assignmane: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
"""