学习参考文档:https://blog.csdn.net/sc_lilei/article/details/80464645
# 三个经典闭包案例
# no 1 闭包函数引用的变量是父函数的参数
def line_conf(a, b):
def line(x):
return a * x + b
return line
# 定义两条直线
line_A = line_conf(2, 1) # y=2x+1
line_B = line_conf(3, 2) # y=3x+2
# 打印x对应y的值
print(line_A(1)) # 3
print(line_B(1)) # 5
# no 2 闭包函数引用的变量时父函数作用域的变量
def lin_conf():
a = 1
b = 2
def line(x):
print(a * x + b)
return line
line = lin_conf()
print(line.__closure__)
for i in line.__closure__: # 打印引用的外部变量值
print(i.cell_contents) # 1 ; #2
# no 3
def _line_(a, b):
def line_c(c):
def line(x):
return a * (x ** 2) + b * x + c
return line
return line_c
print(_line_(1, 2))
闭包可保存运行环境
# 闭包保存运行环境
# 使用闭包来实现输入 1 2 3,函数并未保存变化的外部变量
_list = []
for i in range(3):
def func(a):
return i + a
_list.append(func)
for f in _list:
print(f(1)) # 3 3 3
# 引入闭包,可以保存运行环境中的变量
_list = []
for i in range(3):
def func_count(i):
def func(a):
return i + a
return func
_list.append(func_count(i))
for f in _list:
print(f(1)) # 1 2 3