我定义了一个名为的阶乘函数fab
。我使用生成器来避免堆栈溢出。但是当我尝试编写更直观的装饰器版本时出现了一些我无法理解的问题:
import types
def TCO(f):
def inner(*nkw,**kw):
gen=f(*nkw,**kw)
while isinstance(gen,types.GeneratorType):
gen=gen.next()
return gen
return inner
def fab(n,s=1):
if n<2:
yield s
else:
yield fab(n-1,s*n)
x=TCO(fab)
print x(2500) #this works fine, overcoming the limitation of tail-recursion.
fab=TCO(fab) #now just change the variable name.
print fab(5) #this woks fine.
print fab(2500) #this will raise an error :maximum recursion limit exceeded
为什么?我知道它与同名有关fab
,但为什么fab(5)
可以正常工作?我认为当我定义时fab=TCO(fab)
,我实际上将f
in引用的对象更改inner
为 object TCO(fab)
。所以当 fab(5) 运行时,gen
永远不会是生成器!因为inner
永不返回生成器!
我很生气……为什么?