【发布时间】:2020-06-06 10:54:53
【问题描述】:
下面的代码定义了decorator 和decorated 函数。当我调用修饰函数时,我得到一个 TypeError: unhashable type: 'dict'。哪里有问题?欣赏输入。我在桌面上使用jupyter 笔记本。
def memorize(func):
""" Store the results of a decorated function for last lookup"""
#store results in a dictionary that maps arguments to results
cache = {}
# define the wrappaer function that the decorator returns
def wrapper(*args,**kwargs):
#if these arguments haven't been seen before
if (args, kwargs) not in cache:
cache[(args,kwargs)] = func(*args, **kwargs)
return cache[(args, kwargs)]
return wrapper
@memorize
def slow_function(a,b):
print('Sleeping.....')
time.sleep(5)
return a+b
slow_function(3,7)
TypeError: unhashable type: 'dict'
【问题讨论】:
-
这能回答你的问题吗? TypeError: unhashable type: 'dict'
标签: python-3.x function dictionary