簡體   English   中英

使用緩存在 python 上創建 Memoize 裝飾器

[英]Creating a Memoize decorator on python using cache

我正在使用 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 

我使用帶有以下 function 的裝飾器:

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

錯誤是不可散列的類型字典。 如果有人能解釋這個錯誤的原因,我將不勝感激。

提前致謝。

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM