What is the necessity or usefulness of using an instance variable / function attribute to implement memoization and pass records in each call?

In many memoization examples, I usually see people prefer to make a wrapper or decorator (or some language-dependent variations, such as using a higher-order function to close the memo object) to keep the results of previous function calls in an almost “state”. Such an example can be seen below:

class Memoize(object):
    def __init__(self, func):
        self.func = func
        self.cache = {}
    def __call__(self, *args):
        if args in self.cache:
            return self.cache[args]
        ret = self.func(*args)
        self.cache[args] = ret
        return ret

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

What is the difference between / tradefoff between doing something this way by simply passing a note in the arguments to your function? For example, for example:

def fib(n, memo = {}):
    if (n < 2):
        return 1
    if (n in memo):
        return memo[n]
    memo[n] = fib(n - 1) + fib(n - 2)
    return memo[n]
+4
source share
1 answer

: fib , . fib Memoize memoizing fib ( ).

+2

Source: https://habr.com/ru/post/1694986/


All Articles