闭包:在函数嵌套中,内部函数引用了外部函数的自由变量产生了闭包,自由变量被保留下来而不是随着外部函数消亡
案例一:(python2中的闭包使用)
def fn():
c = [0] #自由变量
def inner():
c[0] += 1
return c[0]
return inner
foo = fn()
print(callable(foo))
print(foo(),foo())
c = 200
print(foo())
运行结果:
True
1 2
3
案例二:(python3中的闭包使用)
def counter():
count = 10 #自由变量
def inc():
nonlocal count
count += 1
return count
return inc
foo = counter()
print(foo(),foo())
运行结果:
11 12