Day10--进阶--闭包
python 一切皆对象: 如 python中一个函数可以作为另外一个函数的参数,传递
🧸闭包:
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('f2()定义', a)
print('f1()打印', a)
f2()
print('调用f2()后', a)
问题:
有一个旅行者,我们要检测其旅行长度 起点x = 0 比如他走3步, result = 3 比如他又走5步, result = 8 比如他走6步, result =14
origin = 0
def go1(step):
global origin
new_pos = origin + step
origin = new_pos
return new_pos
print(go1(3))
print(go1(5))
print(go1(6))
origin = 0
def sum_walk(pos):
def walk(step):
nonlocal pos
new_pos = pos + step
pos = new_pos
return new_pos
return walk
s = sum_walk(origin)
print(s(2))
print(origin)
print(s(5))
print(origin)
闭包知识函数式编程的一种应用
|