# 非闭包 def curve_pre(): def curve(): print('This is a function') return curve f = curve_pre() f()
# 闭包 = 函数 + 环境变量 # 现场 def curve_pre(): a = 25 def curve(x): return a*x*x return curve a = 10 f = curve_pre() print(f(2)) print(f.__closure__) print(f.__closure__[0].cell_contents)
def f1(): a = 10 def f2(): a = 20 print(a) print(a) f2() print(a) f1() print(f.__closure__)
''' 旅行者 x, y x = 0 3 result = 3 5 result = 8 6 result = 14 '''
# 非闭包方法 origin = 0 def go(step): global origin nwe_pos = origin + step origin = nwe_pos return nwe_pos print(go(2)) print(go(5)) print(go(8))
# 闭包实现方法 函数式编程 origin = 0 def factory(pos): def go(step): nonlocal pos nwe_pos = pos + step pos = nwe_pos return nwe_pos return go tourist = factory(origin) print(tourist(2)) print(tourist.__closure__[0].cell_contents) print(tourist(5)) print(tourist.__closure__[0].cell_contents) print(tourist(8))
In [19]:
# 非闭包
def curve_pre():
def curve():
print('This is a function')
return curve
f = curve_pre()
f()
In [24]:
# 闭包 = 函数 + 环境变量
# 现场
def curve_pre():
a = 25
def curve(x):
return a*x*x
return curve
a = 10
f = curve_pre()
print(f(2))
print(f.__closure__)
print(f.__closure__[0].cell_contents)
In [26]:
def f1():
a = 10
def f2():
a = 20
print(a)
print(a)
f2()
print(a)
f1()
print(f.__closure__)
In [47]:
'''
旅行者
x, y
x = 0
3 result = 3
5 result = 8
6 result = 14
'''
Out[47]:
In [56]:
# 非闭包方法
origin = 0
def go(step):
global origin
nwe_pos = origin + step
origin = nwe_pos
return nwe_pos
print(go(2))
print(go(5))
print(go(8))
In [65]:
# 闭包实现方法 函数式编程
origin = 0
def factory(pos):
def go(step):
nonlocal pos
nwe_pos = pos + step
pos = nwe_pos
return nwe_pos
return go
tourist = factory(origin)
print(tourist(2))
print(tourist.__closure__[0].cell_contents)
print(tourist(5))
print(tourist.__closure__[0].cell_contents)
print(tourist(8))
In [ ]: