import time
def outer(F):
def wrapper(x):
start = time.time()
F(x)
end = time.time()
print(end - start)
return wrapper
@outer
def func2(a):
if a == 1:
return 1
else:
return a * func2(a-1)
func2(7)
上面是一段python递归实现阶乘的代码,但是在加上装饰器之后就报错了,想请大家看下问题出在哪里?为什么调用的时候不用 @outer这种方式,而用原始的 outer(func2)(7)就没问题了?
报错如下:
[root@yang python]# python3 test.py
7.152557373046875e-07
Traceback (most recent call last):
File "test.py", line 22, in
func2(7)
File "test.py", line 6, in wrapper
F(x)
File "test.py", line 17, in func2
return a * func2(a-1)
File "test.py", line 6, in wrapper
F(x)
File "test.py", line 17, in func2
return a * func2(a-1)
File "test.py", line 6, in wrapper
F(x)
File "test.py", line 17, in func2
return a * func2(a-1)
File "test.py", line 6, in wrapper
F(x)
File "test.py", line 17, in func2
return a * func2(a-1)
File "test.py", line 6, in wrapper
F(x)
File "test.py", line 17, in func2
return a * func2(a-1)
File "test.py", line 6, in wrapper
F(x)
File "test.py", line 17, in func2
return a * func2(a-1)
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
本文探讨了一段使用装饰器的Python递归阶乘代码出现的问题。当使用特定语法调用带装饰器的递归函数时,程序会抛出错误。文章分析了问题原因,并对比了不同调用方式的效果。
2008

被折叠的 条评论
为什么被折叠?



