Python闭包
闭包的定义:闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数。这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它的环境也不例外。所以,闭包是由函数和与其相关的引用环境组合而成的实体。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#! /usr/bin/env python
def closuretesting():
b = 15
c = 20
print 'b id %x'% id(b)
print 'c id %x'% id(c)
def line(x):
return 2*x + b + c
return line
testline=closuretesting()
print(testline.__closure__) # 这个属性中的值,你会发现正好为b 和 c的ID ,因此可以得知,闭包是通过这个属性去记录类似于b,c这样的变量的
print(testline.__closure__.cell_contents)# __closure__里包含了一个元组(tuple),这个元组中的每个元素是cell类型的对象
print(testline.__closure__.cell_contents)
print(testline(10))
output
1
2
3
4
5
6
b id 1026008
c id 1025f90
(<cell at 0x7f5efed66d38: int object at 0x1026008>, <cell at 0x7f5efed66d70: int object at 0x1025f90>)
15
20
55
闭包的判断:
(1)一个嵌套函数(函数里面的函数)
(2)嵌套函数用到封闭函数里定义的一个或多个值
(3)封闭函数的返回值是嵌套函数
页:
[1]