python函数的闭包问题(内嵌函数)
> def func1(): ... print ('func1 running...') ... def func2(): ... print ('func2 running...') ... func2() ... > func1() func1 running... func2 running...
内部函数func2作用域都在外部函数func1作用域之内
如果试图在外部函数的外部调用内部函数将会报错
> func2() Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'func2' is not defined
关于python的闭包问题
如果试图在一个内部函数里对外部作用域(不包括外部函数的外部作用域)的变量进行引用,内部函数就会被认为是闭包
> def FuncX(x): ... def FuncY(y): ... return x*y ... return FuncY
对于FuncY函数来说,对在FuncX函数的整个作用域(FuncY函数的非全局作用域的外部作用)的变量x进行引用,自此就可以说FuncY函数就是所谓的闭包
> f = FuncX(8) > f <function FuncY at 0x7f3a436fc2a8> > type(f) <type 'function'> > f(10) 80 > FuncX(7)(8) 56
由于闭包本身是基于内部函数这一概念而来,所以不能在外部函数的外部作用域对内部函数进行调用
> FuncY(8) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'FuncY' is not defined
既然是基于内部函数这一概念而来,自然对于内部函数来说对引用外部函数作用域内的变量进行修改,将会启动解释器的屏蔽机制
> def Func1(): ... x = 233 ... def Func2(): ... x *=x ... return x ... return Func2() ... > Func1() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 6, in Func1 File "<stdin>", line 4, in Func2 UnboundLocalError: local variable 'x' referenced before assignment
x*=x的左值此时是内部函数作用域里的变量,此时试图将没有定义的数据进行平方操作,因此报错
> def Func1(): ... x = 233 ... def Func2(): ... x = 321 ... return x ... return Func2() ... > Func1() 321
内部函数创建x变量并且屏蔽外部函数作用域内的x变量
python3之前的解决办法
应用容器类型(list,tuple之类的)存放外部函数作用域的变量从而不会被屏蔽机制屏蔽掉,因为容器类型不是存放在栈里面
> def Func1(): ... x = [233] ... def Func2(): ... x[0] *= x[0] ... return x[0] ... return Func2() ... > Func1() 54289
python3之后的解决办法:nonlocal关键字
> def Func1(): ... x = 233 ... def Func2(): ... nonlocal x ... x *= x ... return x ... return Func2() ... > Func1() 54289
以上所述是小编给大家介绍的python函数的闭包问题详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
金钱帮资源网 Copyright www.kbjia.com
暂无“详解python函数的闭包问题(内部函数与外部函数详述)”评论...
更新日志
2024年10月07日
2024年10月07日
- 班得瑞原装进口《第二张新世纪专辑:寂静山林》1CD[APE/CUE分轨][327.1MB]
- Beyond.1989-真的见证(2024环球MQA-UHQCD限量版)【环球】【WAV+CUE】
- 陈怡婷.2024-予你的心谁来赔【福茂】【FLAC分轨】
- 陈冠希.2003-HITS.OR.MISSES【英皇娱乐】【WAV+CUE】
- 班得瑞原装进口《第三张新世纪专辑:春野》1CD[APE/CUE分轨][278.9MB]
- 班得瑞原装进口《第四张新世纪专辑:蓝色天际》1CD[APE/CUE分轨][284.8MB]
- 班得瑞原装进口《第五张新世纪专辑:迷雾森林+EP》1CD[APE/CUE分轨][334.2MB]
- 田震.1997-顺其自然(日版)【红星生产社】【WAV+CUE】
- 小虫.1996-想得太美【滚石】【WAV+CUE】
- 谢采妘.2016-邓丽君名曲专辑【丰荣】【WAV+CUE】
- 张含韵.2007-一人一梦【天中文化】【WAV+CUE】
- 蟑螂乐队.1999-帮个忙【福茂】【WAV+CUE】
- 张宇.2001-替身【EMI百代】【WAV+CUE】
- 班得瑞原装进口《第六张新世纪专辑:日光海岸》1CD[APE/CUE分轨][339.5MB]
- 班得瑞原装进口《第七张新世纪专辑:梦花园》1CD[APE/CUE分轨][331.4MB]