Python中的内部函数和闭包

Python支持函数内嵌

>>> def fun1():
	print('fun1()正在被调用...')
	def fun2():
		print('fun2()正在被调用...')
	fun2()

	
>>> fun1()
fun1()正在被调用...
fun2()正在被调用...
>>> fun2()
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    fun2()
NameError: name 'fun2' is not defined

我们可以看到,fun2()智能通过fun1()来进行调用,而不能直接调用fun2()


闭包

>>> def FunX(x):
	def FunY(y):
		return x * y
	return FunY

>>> i = FunX(8)
>>> i
<function FunX.<locals>.FunY at 0x000001A770A2D8C8>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> FunX(8)(5)
40

或者直接用FunX(8)(5)把x赋值为8,把y赋值为5

>>> def Fun1():
	x = 5
	def Fun2():
		x *=x
		return x
	return Fun2()

>>> Fun1()
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    Fun1()
  File "<pyshell#44>", line 6, in Fun1
    return Fun2()
  File "<pyshell#44>", line 4, in Fun2
    x *=x
UnboundLocalError: local variable 'x' referenced before assignment

在内部函数Fun2()中,想利用Fun1()中的x的值,最后发现系统报错,因为Fun2()中的x对于Fun1()来说是局部变量。

那么怎么解决这个问题呢?

>>> def Fun1():
	x = [5]
	def Fun2():
		x[0] *= x[0]
		return x[0]
	return Fun2()

>>> Fun1()
25

这是因为列表不是存储在栈中的。

那么还可以怎么解决呢?

>>> def Fun1():
	x = 5
	def Fun2():
		nonlocal x
		x *=x
		return x
	return Fun2()

>>> Fun1()
25

我们可以看到,可以用nonlocal x 来规定x不是局部变量,那么也可以实现上面的要求

猜你喜欢

转载自blog.csdn.net/liu_hong_yan/article/details/114937417