闭包求解
origin = 0def factory(pos):
def go(step):
nonlocal pos
new_pos = pos + step
pos = new_pos
return new_pos
return go
tourist = factory(origin)
print(tourist(2))
print(tourist(3))
哪位大佬给解释下这段代码啊! 斐波那契数列? origin = 0
def factory(pos):
def go(step):
nonlocal pos
new_pos = pos + step #假定pos = 0 ,step = 2
pos = new_pos #pos = 2
return new_pos #返回2的值给go函数
return go #返回go函数地址给factory函数。
tourist = factory(origin) #实例化调用go函数(上面return的是go函数地址,必须赋值才能调用)
print(tourist(2)) #假定的过程,结果为2
print(tourist(3)) #被实例化绑定,pos没有释放掉,仍旧为2,setp为3,结果为5。 heidern0612 发表于 2018-12-23 19:32
感谢
页:
[1]