我正在使用 Datacamp 课程来学习装饰器,我承认我对缓存主题还很陌生。
让我陷入困境的是,我在他们的课程中遵循“示例”记忆装饰器,它在 jupyter 笔记本上抛出错误,尽管它与他们的课程完全相同:
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
错误是unhashable类型的dict。如果有人能解释这个错误的原因,我将非常感激。
提前致谢。
试试这个:
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
Python 中的字典对其键有一些先决条件,请参阅:https://wiki.python.org/moin/DictionaryKeys
解决方案是将参数从各种类型转换为可哈希类型,例如字符串。