闭包函数
闭包函数就是返回值是函数的函数
# _*_coding:utf-8 _*_
#求和函数lazy_sum()的返回值是求和函数sum(),所以需要再次调用sum()函数才能算出结果
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax += n
return ax
return sum
L = lazy_sum(2, 3, 4, 5)()
print(L)
#返回函数不要引用任何循环变量,或者后续会发生的变量。需要用到循环时,应该把循环放在返回函数之外
def count():
def f(j):
def g():
return j * j
return g
fs = []
for i in range(1, 4):
fs.append(f(i))
return fs
f1, f2, f3 = count()
print(f1())
print(f2())
print(f3())
# 练习:利用闭包返回一个计数器函数,每次调用它返回递增整数:
# 解法1 定义一些列表,往里面不断的添加最后一个元素+1的值
def createCounter1():
L = [0]
def counter():
i = L[-1]
L.append(i + 1)
return L[-1]
return counter
counterA = createCounter1()
if [counterA(), counterA(), counterA(), counterA()] == [1, 2, 3, 4]:
print('pass')
else:
print('failed')
# 解法2 创建只有一个元素的列表,每次替换这个元素
def createCounter2():
L = [0]
def counter():
L[0] += 1
return L[0]
counterB = createCounter1()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
print('pass')
else:
print('failed')
# 解法3:创造一个生产器,每次调用函数时调用生成器来取值
def createCounter3():
def f():
n = 0
while True:
n += 1
yield n
sum = f()
def counter():
return (next(sum))
return counter
counterC = createCounter3()
if [counterC(), counterC(), counterC(), counterC()] == [1, 2, 3, 4]:
print('pass')
else:
print('failed')