本文主要是介绍Python系列之闭包,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
什么是闭包
闭包(closure)是函数式编程的重要的语法结构。函数式编程是一种编程范式 (而面向过程编程和面向对象编程也都是编程范式)。在面向过程编程中,我们见到过函数(function);在面向对象编程中,我们见过对象(object)。函数和对象的根本目的是以某种逻辑方式组织代码,并提高代码的可重复使用性(reusability)。闭包也是一种组织代码的结构,它同样提高了代码的可重复使用性。2
In conclusion here are the three criteria’s for a closure:1
闭包有如下三个特点
- There must be a nested function (a function inside another function).
必须有一个嵌套函数(一个函数在另一个函数中) - This nested function has to refer to a variable defined inside the enclosing function.
这个嵌套函数必须引用在封闭函数中定义的变量 - The enclosing function must return the nested function.
封闭函数必须返回嵌套函数
闭包的案例
关于什么是闭包,看起来可能比较抽象,但是举个例子就很容易理解。
#闭包函数的实例
#function_outside是外部函数,msg是外函数的临时变量
def function_outside():msg = 'Hello'#function_inside是内函数def function_inside():#内函数中用到了外函数的临时变量return msg#外函数的返回值是内函数的引用return function_inside
function_outside是外部函数;在function_outside的内部,我们定义了一个function_inside,这个函数也被称为嵌套函数。符合第一个特点:必须有一个嵌套函数。
function_inside引用了function_outside函数中的临时变量msg。符合第二个特点:这个嵌套函数必须引用在封闭函数中定义的变量。
return function_inside 返回了嵌套函数。符合第三个特点:封闭函数必须返回嵌套函数。
我们称msg为function_inside的环境变量,虽然function_inside引用了msg,但msg并不是定义在function_inside中的变量,而是定义在外部函数中。
在一个外函数(function_outside)中定义了一个内函数(function_inide),内函数里引用了外函数的变量(msg),并且外函数的返回值是内函数的引用。这样就构成了一个闭包。
- 在Python中,环境变量取值被保存在函数对象的__closure__属性中。代码如下:
def function_outside():msg = 'Hello'def function_inside():return msgreturn function_insidemy_function = function_outside()
print(my_function.__closure__)
print(my_function.__closure__[0].cell_contents)
__closure__里包含了一个元组(tuple)。这个元组中的每个元素是cell类型的对象。我们看到第一个cell包含的就是字符串’hello’,也就是我们创建闭包时的环境变量msg的取值。
- 外函数的返回值是内函数的引用
关于这句话怎么理解?
当我们在python中定义一个函数def demo():的时候,内存中会分配一些空间,存下这个函数的代码、内部的变量等。
demo只不过是一个变量的名字,它里面存了这个函数所在位置的引用而已。我们还可以进行x = demo,y = demo,这样x和y都指向了demo函数所在的引用。
在这之后我们可以用x() 或者 y() 来调用我们自己创建的demo() ,调用的实际上根本就是一个函数,x、y和demo三个变量名存了同一个函数的引用。
有了上面的解释,我们再来看“外函数的返回值是内函数的引用“这句话,就比较好理解了。如下截图中,我们看见my_function的name返回的是function_inside这个函数的名称。
def function_outside():msg = 'Hello'def function_inside():return msgreturn function_insidemy_function = function_outside()
print(my_function.__name__)'''
运行结果:
function_inside
'''
使用闭包注意事项
- 闭包无法修改外包函数的局部变量
def function_outside():msg = 'Hello'def function_inside():msg = 'Hi'print('inner msg:',msg)print('msg before call inner:',msg)function_inside()print('msg after call inner:',msg)'''
运行结果:
msg before call inner: Hello
inner msg: Hi
msg after call inner: Hello
'''
从运行结果可以看出,虽然function_inside函数里面也定义了一个局部变量msg,但是不会改变外部函数中的局部变量msg
要修改也很简单,可以在内函数中用nonlocal关键字声明,表示这个变量不是内部函数的变量,需要向上一层变量空间找这个变量
def function_outside():msg = 'Hello'def function_inside():nonlocal msgmsg = 'Hi'print('inner msg:',msg)print('msg before call inner:',msg)function_inside()print('msg after call inner:',msg)
- 使用闭包的过程中,一旦外函数被调用一次返回了内函数的引用,虽然每次调用内函数,是开启一个函数执行过后消亡,但是闭包变量实际上只有一份,每次开启内函数都在使用同一份闭包变量
def outer(x):def inner(y):nonlocal xx += yreturn xreturn innera = outer(10)
print(a(1))
print(a(3))'''
运行结果:
11
14
'''
- 返回函数尽量不要引用循环变量或者会发生变化的变量
def outer():result_list = []for i in range(3):def inner():return i*iresult_list.append(inner)return result_listresult = outer()
for item in result:print(item())'''
运行结果:
4
4
4
'''
我们希望是返回0,1,4,但是结果确是4,4,4.原因就是当把函数加入result_list列表的时候,i还没有执行。等函数执行的时候,再去找i的值,这个时候i的值已经是2,所以结果是4,4,4
如果一定要引用循环变量怎么办?方法是用函数的参数绑定循环变量当前的值,无论该循环变量后续如何更改,已绑定到函数参数的值不变:
def outer():result_list = []for i in range(3):def inner(x = i):return x*xresult_list.append(inner)return result_listresult = outer()
for item in result:print(item())'''
运行结果:
0
1
4
'''
参考
- [1] Python Closures
- [2] Python深入04 闭包
- [3] Python中的闭包实例详解
- [4] 谈谈自己的理解:python中闭包,闭包的实质
- [5] 函数式编程初探
文章也发布于我的博客,欢迎大家阅读。
这篇关于Python系列之闭包的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!