1、什么是闭包?
- 把一个函数的参数,传递到另外一个函数里,同时一个函数当做另外一个函数的返回结果。
即:闭包 = 函数 + 环境变量
下面我们看一个例子:
def curvs_pre():
#定义一个环境变量
a = 2
def curvs(x):
return a*x*x
return curvs
f = curvs_pre()
#用__closure__查看闭包的环境变量,返回的是对象
print(f.__closure__)
# 用__closure__[0].cell_contents查看闭包环境变量的值
print(f.__closure__[0].cell_contents)
print(f(2))
结果:
(<cell at 0x0000016556F2F2E8: int object at 0x000000005C6DE9F0>,)
2
8
2、一个示例看看闭包
# 这个不是闭包
'''
def f1():
a = 10
def f2():
#此a被python认为局部变量,不能影响局部外的变量
a = 20
print("-----1-----",a)
print("--------2-------",a)
f2()
print("--------3-----",a)
f1()
'''
# 这个才是闭包
def f1():
# 环境变量
a = 10
def f2():
c = 20 * a
return f2
f = f1()
print(f.__closure__)
print(f())
'''
1、什么是闭包?
闭包 = 函数 + 环境变量
即定义函数f1,同时在f1函数中定义一个环境变量a,并且在f1函数中定义一个内函f2,在f2中引用环境变量a。在函数f1中,返回f2函数(return f2)
'''
结果:
--------2------- 10
-----1----- 20
--------3----- 10
**************************************************
(<cell at 0x0000020D4912F2E8: int object at 0x000000005C6DEAF0>,)
None
3、出一个题目
题目:计算旅行者的步数,比如一名旅行者第一次走了两步,第二次走了三步,第三次走了五步,那么整个过程应该走了10步。即这个计算其实就是旅行者每走一次,就累加一次数据。
- 不用闭包的去解决问题
initial = 0
def distance(pow):
global initial
new_pows = initial + pow
initial = new_pows
return new_pows
print(distance(2))
print(distance(3))
print(distance(5))
结果:
2
5
10
2.用闭包去解决问题
initial = 0
def distance(pos):
def go(step):
nonlocal pos
new_pows = pos + step
pos = new_pows
return new_pows
return go
restul = distance(initial)
print(restul(2))
print(restul(3))
print(restul(5))
结果:
2
5
10