12.python-使用非当前作用域变量的方法
# 全局变量(global variable)& 非本地局部变量(nonlocal variable)
# 关键字global&nonlocal
# ===================================================
gcount = 0
def global_test():
try:
gcount += 1
print(gcount)
except Exception as e:
print(str(Exception)) # <class 'Exception'>
print(str(e)) # local variable 'gcount' referenced before assignment
print('Do not declare the global variable before changing it:')
global_test()
# 运行异常:
# UnboundLocalError: local variable 'gcount' referenced before assignment
# ===================================================
# 在函数内部 修改 全局变量之前,必须先再次声明全局变量,正确打开方式如下
def global_test_1():
global gcount
gcount += 1
print(gcount)
print('Declare the global variable before changing it:')
global_test_1() # 1
# ===================================================
# 若不修改全局变量,可不在局部声明全局变量
def global_test_2():
print(gcount)
print('Needn\'t declare the global variable before referencing it:')
global_test_2() # 1
# ===================================================
# 局部变量的用法
def outer():
count = 0
def inner():
def inner_in():
nonlocal count # 修改非当前作用域且非全局变量,必须声明,若只是引用,不必声明
count += 1
return count
return inner_in()
return inner
inner_func = outer()
print(inner_func()) # 1
print(inner_func()) # 2
print(inner_func()) # 3
inner_func_1 = outer()
print(inner_func_1()) # 1
print(inner_func_1()) # 2
print(inner_func_1()) # 3