闭包

1. 函数引用

 1 def test1():
 2     print("--- in test1 func----")
 3 
 4 # 调用函数
 5 test1()
 6 
 7 # 引用函数
 8 ret = test1
 9 
10 print(id(ret))
11 print(id(test1))
12 
13 #通过引用调用函数
14 ret()

  运行结果:

1 --- in test1 func----
2 140212571149040
3 140212571149040
4 --- in test1 func----

2. 什么是闭包

 1 # 定义一个函数
 2 def test(number):
 3 
 4     # 在函数内部再定义一个函数,并且这个函数用到了外边函数的变量,那么将这个函数以及用到的一些变量称之为闭包
 5     def test_in(number_in):
 6         print("in test_in 函数, number_in is %d" % number_in)
 7         return number+number_in
 8     # 其实这里返回的就是闭包的结果
 9     return test_in
10 
11 
12 # 给test函数赋值,这个20就是给参数number
13 ret = test(20)
14 
15 # 注意这里的100其实给参数number_in
16 print(ret(100))
17 
18 #注 意这里的200其实给参数number_in
19 print(ret(200))

  运行结果:

1 in test_in 函数, number_in is 100
2 120
3 
4 in test_in 函数, number_in is 200
5 220

3. 看一个闭包的实际例子:

1 def line_conf(a, b):
2     def line(x):
3         return a*x + b
4     return line
5 
6 line1 = line_conf(1, 1)
7 line2 = line_conf(4, 5)
8 print(line1(5))
9 print(line2(5))

这个例子中,函数line与变量a,b构成闭包。在创建闭包的时候,我们通过line_conf的参数a,b说明了这两个变量的取值,这样,我们就确定了函数的最终形式(y = x + 1和y = 4x + 5)。我们只需要变换参数a,b,就可以获得不同的直线表达函数。由此,我们可以看到,闭包也具有提高代码可复用性的作用。

如果没有闭包,我们需要每次创建直线函数的时候同时说明a,b,x。这样,我们就需要更多的参数传递,也减少了代码的可移植性。

注意点:

由于闭包引用了外部函数的局部变量,则外部函数的局部变量没有及时释放,消耗内存

4. 修改外部函数中的变量

python3的方法

 1 def counter(start=0):
 2     def incr():
 3         nonlocal start
 4         start += 1
 5         return start
 6     return incr
 7 
 8 c1 = counter(5)
 9 print(c1())
10 print(c1())
11 
12 c2 = counter(50)
13 print(c2())
14 print(c2())
15 
16 print(c1())
17 print(c1())
18 
19 print(c2())
20 print(c2())

python2的方法

 1 def counter(start=0):
 2     count=[start]
 3     def incr():
 4         count[0] += 1
 5         return count[0]
 6     return incr
 7 
 8 c1 = closeure.counter(5)
 9 print(c1())  # 6
10 print(c1())  # 7
11 c2 = closeure.counter(100)
12 print(c2())  # 101
13 print(c2())  # 102
原文地址:https://www.cnblogs.com/zzmx0/p/12747560.html