Python中关键字nonlocal和global的用法及区别

一、Python3中globalnonlocal 用法

nonlocal
首先,要明确 nonlocal 关键字是定义在闭包里面的(不定义在闭包里会抛异常SyntaxError: nonlocal declaration not allowed at module level)。请看以下代码:

x = 0
def outer():
	x = 1
	def inner():
		x = 2
		print("inner:", x)

	inner()
	print("outer:", x)

outer()
print("global:", x)

结果:

inner: 2
outer: 1
global: 0

现在,在闭包里面加入nonlocal关键字进行声明:

x = 0
def outer():
	x = 1
	def inner():
		nonlocal x
		x = 2
		print("inner:", x)

	inner()
	print("outer:", x)

outer()
print("global:", x)

结果:

inner: 2
outer: 2
global: 0

看到区别了么?这是一个函数里面再嵌套了一个函数。当使用 nonlocal 时,就声明了该变量不只在嵌套函数inner()里面才有效, 而是在整个大函数里面都有效。
global
还是一样,看一个例子:

x = 0
def outer():
	x = 1
	def inner():
		global x
		x = 2
		print("inner:", x)

	inner()
	print("outer:", x)

outer()
print("global:", x)

结果:

inner: 2
outer: 1
global: 2

global 是对整个环境下的变量起作用,而不是对函数类的变量起作用。

二、Python3中globalnonlocal区别

一句话解释:nonlocal,如果在闭包内给该变量赋值,那么修改的其实是闭包外那个作用域中的变量。global,用来表示对该变量的赋值操作,将会直接修改模块作用域里的那个变量。(nonlocalglobal互为补充)——来自《Effective Python》
转自:
https://www.jb51.net/article/108183.htm
http://www.cnblogs.com/brad1994/p/6533267.html

猜你喜欢

转载自blog.csdn.net/qq_36528804/article/details/82961398