Python中的内部函数和闭包

本文探讨了Python中函数内嵌的特性及其限制,并详细介绍了闭包的概念及其实现方式,包括如何解决内部函数访问外部变量的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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不是局部变量,那么也可以实现上面的要求

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值