11-11 一个事例看看闭包
11-12 闭包的经典误区
# 11-11 一个事例看看闭包
# 11-12 闭包的经典误区
# 闭包 = 函数+环境变量(定义时候的变量)
# 不仅有返回值,而且还有现场
def curve_pre():
a = 25
def curve(x):
return a*x*x
return curve
a = 10
f = curve_pre()
print(f.__closure__)#闭包的结果存放的地方
print(f.__closure__[0].cell_contents)
print(f(2))
# 看看下面代码,理解意义
def f1():
a = 10
def f2():
# 此时将被Python认为是一个局部变量
a = 20
print(a)
print(a)
f2()
print(a)
f1()
# 打印结果如图1,上述代码执行的时候,一定是由外到里。想想打印结果!!!
# 看看下面的闭包的形式!!!
def f1():
a = 10
def f2():
# 此时将被Python认为是一个局部变量
a = 20
return a
return f2
f = f1()
print(f)
f1(f.__closure__)
# 这种情况不属于闭包,a = 20,并没有引用外部变量。所以不是闭包只是会被当成局部变量。
# 第二个函数里的a,一定要去引用,不能去赋值。否则就不是闭包
网友评论