python - python装饰器如何与递归一起工作?

标签 python recursion decorator python-decorators

我有下面的代码

def memo(fn):
    cache = {}
    miss = object()
    print 'MEMO'
    def wrapper(*args):
        result = cache.get(args, miss)
        print 'IT CALLS'
        if result is miss:
            print 'IT MISSES'
            result = fn(*args)
            cache[args] = result
        return result
    return wrapper

@memo
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

当我调用 fib(4) 时,它只打印一次 MEMO。以下是输出。

MEMO
IT CALLS
IT MISSES
IT CALLS
IT MISSES
IT CALLS
IT MISSES
IT CALLS
IT MISSES
IT CALLS
IT MISSES
IT CALLS
IT CALLS

是什么导致了这种行为??

最佳答案

这是正确的行为,与递归无关。

MEMO 在装饰器被调用时打印,当它应用于函数时;即,在定义时。如果您根本不调用 fib(),MEMO 仍会被打印出来。

关于python - python装饰器如何与递归一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34041715/

相关文章:

javascript - 如何在 JavaScript 中从外部停止递归循环函数?

list - 使用递归将列表分解为子列表

angular - Typescript + Angular 2 : How can I ensure emitted decorator metadata will refer to variables in scope, 以避免 "not defined"错误?

python - 使用 hex 和 ascii 混合接收的 UDP 字节;如何解码?

python - 当 for 循环的变量有一段时间条件时,如何在 for 循环中获得步骤跳转

list - 递归定义init函数

python - 装饰器不应该有副作用吗?

python - 向所有 python 异常添加额外信息

python - 将 Pandas 数据框重组为 basemap 的网格

python - 如何注册MultipleModelAPIView?