【问题标题】:Creating a Memoize decorator on python using cache使用缓存在 python 上创建 Memoize 装饰器
【发布时间】:2020-11-29 18:55:03
【问题描述】:

我正在使用 Datacamp 课程来学习装饰器,我承认我对缓存这个主题还很陌生。

让我陷入困境的是我在他们的课程中遵循“示例”记忆装饰器,即使它与他们的课程完全相同,它也会在 jupyter notebook 上引发错误:

def memoize(func):
    '''Store the results of the decorated function for fast look up'''
    #Store results in a dict that maps arguments to results
    cache = {}
    #As usual, create the wrapper to create the newly decorated function
    def wrapper(*args, **kwargs):
        # If these arguments havent been seen before...
        if (args, kwargs) not in cache:
            #Call func() and store the result.
            cache[(args, kwargs)] =func(*args, **kwargs)
        #Now we can look them up quickly
        return cache[(args, kwargs)]
    
    return wrapper 

我使用具有以下功能的装饰器:

@memoize
def slow_function(a,b):
    print('Sleeping...')
    time.sleep(5)
    return a+b

错误是不可散列的类型字典。如果有人能解释这个错误的原因,我将不胜感激。

提前致谢。

【问题讨论】:

    标签: python function decorator


    【解决方案1】:

    试试这个:

    import time
    
    def memoize(func):
        """
        Store the results of the decorated function for fast lookup
        """
        # store results in a dict that maps arguments to results
        cache = {}
        # define the wrapper function to return
        def wrapper(*args, **kwargs):
            # if these arguments haven't been seen before
            if (str(args), str(kwargs)) not in cache:
                # call func() and store the result
                cache[(str(args), str(kwargs))] = func(*args, **kwargs)
            return cache[(str(args), str(kwargs))]
        return wrapper
    
    
    @memoize
    def slow_function(a, b):
        print('Sleeping...')
        time.sleep(5)
        return a + b
    

    【讨论】:

    • 虽然这是正确的,但最好能解释一下为什么 OP 中的代码不起作用以及为什么你的代码起作用。稍后看到此答案的人将从解释中受益。
    猜你喜欢
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 2017-11-16
    • 2010-12-15
    • 2022-09-29
    • 2015-08-23
    相关资源
    最近更新 更多