闭包
def curve_pre():
def curve():
print('This is a function')
return curve
f = curve_pre()
f() #This is a functiondef curve_pre1():
a = 25
def curve1(x):
return a*x**2
return curve1
#闭包 = 函数 + 环境变量(函数定义的时候)
a = 20 #全局变量
f1 = curve_pre1()
print(f1.__closure__)
#(<cell at 0x00000216457D06D8: int object at 0x00007FFEF75AD720>,)实质返回了一个闭包
print(f1.__closure__[0].cell_contents) #25 取出环境变量
f1(2)
print(f1(2)) #100 调用时 a 取 25Last updated
Was this helpful?