【发布时间】: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
错误是不可散列的类型字典。如果有人能解释这个错误的原因,我将不胜感激。
提前致谢。
【问题讨论】: