闭包 = 环境变量 + 函数
调用闭包内部的环境变量
def curve_pre():
b = 10
c = 106
def curve(x):
return b*c*x*x
return curve
f = curve_pre()
print(f.__closure__)
print(f.__closure__[0].cell_contents)
print(f(1))
# (<cell at 0x00FDF950: int object at 0x591E4720>, <cell at 0x00FDF9B0: int object at 0x591E4D20>)
# 10
# 1060
闭包的经典误区
def curve_pre():
a = 10
def curve(x):
# a被python认为是环境变量,所以构不成闭包
a = 20
return curve
f = curve_pre()
print(f.__closure__) # None
闭包与非闭包实现人类走路
- 非闭包
a = 0
# global引用全局变量
def go(value):
global a
newtext = a + value
a = newtext
return newtext
print(go1(1))
print(go1(2))
print(go1(3)) # 1 3 6
- 闭包
oragin = 0
def factory(args):
def go(post):
nonlocal args
newPost = post+ args
args = newPost
return args
return go
f = factory(oragin)
print(f(1))
print(f(2))
print(f(3))
网友评论