python decorator如何与递归一起使用?(How python decorator works with recursion?)

我有下面的代码

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

是什么导致了这种行为?

I have the below code

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)

when I call fib(4) it prints MEMO only once. Following is the output.

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

What is causing this behaviour ??

最满意答案

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

调用装饰器时会打印MEMO,将其应用于函数时会发生这种情况; 即在定义时间。 如果您从未调用过fib() ,则仍会打印MEMO。

This is the correct behaviour and has nothing to do with recursion.

MEMO is printed when the decorator is called, which happens when it is applied to a function; ie, at definition time. If you never called fib() at all, MEMO would still be printed.

更多推荐