Python递归的问题?

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 <module>
    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'
阅读 3.4k
2 个回答

内层应该有返回值

def outer(F):
    def wrapper(x):
        start = time.time()
        ret=F(x)
        end = time.time()
        print(end - start)
        return ret # 内层应该有返回值        
    return wrapper
>>> func2(7)
0.0
0.015625
0.015625
0.03125
0.03125
0.03125
0.046875
5040
新手上路,请多包涵

你好,
装饰以前的outer(func2)(7) 和装饰以后的func2(7)当然不一样。
outer(func2) = 新的函数。outer只一次运行。
func2(7) = outer(func2(7)) = outer(func2(outer(func2(6))))。。。每一次func2运行,outer也运行。
对不起,我的中文真不好,希望你能明白。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进