码迷,mamicode.com
首页 > 编程语言 > 详细

Python自学之函数内嵌和闭包

时间:2018-01-19 21:28:23      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:3.0   reference   rac   nonlocal   erro   关键字   一个   从表   就是   

函数内嵌指一个函数内部包含定义另一个函数
举例:

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

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

闭包(closure)是函数式编程的一个重要的语法结构,函数式编程是一种编程范式,著名的函数式编程语言就是LISP语言.
Python中的闭包从表现形式上定义为:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就是被认为闭包.
举例

>> def FunX(x):
def FunY(y): //FunY就是FunX的内部函数,FunX的整个函数作用域为FunY的外部作用域,变量x
return x * y
return FunY

>> i = FunX(8)
>> i //i是一个function
<function FunX.<locals>.FunY at 0x029CDCD8>
>> type(i)
<class ‘function‘>
>> i(5)
40
>> FunX(8)(5)
40
>> FunY(5)
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
FunY(5)
NameError: name ‘FunY‘ is not defined

内部函数对外部函数的局部变量只能进行引用,不能进行修改
举例:

>> def Fun1():
x = 5
def Fun2():
x *= x //x为外部函数的局部变量,只能引用不能修改
return x
return Fun2()

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

解决办法
方法一:
容器类型存放解决,容器类型不是存放在栈中

>> def Fun1():
x = [5] //用列表来存放x
def Fun2():
x[0] *= x[0]
return x[0]
return Fun2()

>> Fun1()
25
>>
方法二
nonlocal关键字,3.0以后版本加入
>> def Fun1():
x = 5
def Fun2():
nonlocal x
x *= x
return x
return Fun2()

>> Fun1()
25
>>

Python自学之函数内嵌和闭包

标签:3.0   reference   rac   nonlocal   erro   关键字   一个   从表   就是   

原文地址:http://blog.51cto.com/10991728/2062995

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!