python关于的闭包代码实例
闭包(以一个函数里面还有一个函数说明)
只用在第二个函数引用了包含着它的第一个函数定义的变量时,这才叫做闭包
---------------------------------------------------------------------------------------------------------------------------------
以函数返回
def curve_pre(): def curve(): print("This is a function") return curve f = curve_pre() f()
输出:This is a function
---------------------------------------------------------------------------------------------------------------------------------
闭包 = 函数 + 函数变量(函数定义时候) def curve_pre(): a = 25 def curve(x): return a*x*x return curve a = 10 f = curve_pre() print(f(2))
输出:100
---------------------------------------------------------------------------------------------------------------------------------
没有形成闭包情况
a = 25 def curve_pre(): def curve(x): return a*x*x return curve a = 10 f = curve_pre() print(f(2))
输出:40
---------------------------------------------------------------------------------------------------------------------------------
闭包说明
def curve_pre(): b = 1 a = 25 def curve(x): return a*x*x+b return curve a = 10 f = curve_pre() print(f.__closure__) print(f.__closure__[0].cell_contents) print(f.__closure__[1].cell_contents) print(f(2))
输出(
25
1
101
说明只有在curve函数里用的上一层函数的参数(即时curve_pre()里面)
---------------------------------------------------------------------------------------------------------------------------------
非闭包(局部变量)
def f1(): a = 10 def f2(): a = 20 print(a) print(a) f2() print(a) f1()
输出:
10
20
10
---------------------------------------------------------------------------------------------------------------------------------
旅行者 从一开始出去
先走2步,共2步;再走3步,共5步;最后走6步,共11步
#全局变量 # origin = 0 # def go(step): # global origin # new_pos = origin + step # origin = new_pos # return origin # # print(go(2)) # print(go(3)) # print(go(6))
#闭包 #并没有改变origin的值,origin一直都是0 origin = 0 def factory(pos): def go(step): nonlocal pos #不是局部变量 new_pos = pos + step pos = new_pos return pos return go turist = factory(origin) print(turist(2)) print(turist(3)) print(turist(6))
#并没有改变origin的值,origin一直都是0
上一篇: 南瓜子孕妇能吃吗