python局部变量、全局变量,global、nolocal的区别

def fun1():
x = 5 # 非全局变量的外部变量,在fun2()的外部作用域里边
def fun2():
x *= x # 会报错未定义
return x
return fun2()
fun1()

解决办法1:用容器存放,因为容器类型不是存放在栈里边(局部变量存放在栈里边),所以不会被屏蔽起来
def fun2():
x = [5]
def fun2():
x[0] *= x[0]
return x[0]
return fun2()
fun2()
解决办法2:用nolocal
def fun3():
x = 5
def fun2():
nonlocal x # 不能用global x,因为x不是全局变量
x *= x
return x
return fun2()
fun3()

global关键字修饰变量后标识该变量是全局变量,对该变量进行修改就是修改全局变量,而nonlocal关键字修饰变量后标识该变量是上一级函数中的局部变量,如果上一级函数中不存在该局部变量,nonlocal位置会发生错误。


猜你喜欢

转载自www.cnblogs.com/wisir/p/12424064.html