我有这个代码,当我打印它时,我遇到了这个错误。有人可以告诉我如何解决这个问题吗?
def memoize(func):
"""Store the results of the decorated function for fast lookup
"""
# Store results in a dict that maps arguments to results
cache = {}
def wraper(*args, **kwargs):
if (args, kwargs) not in cache:
cache[(args, kwargs)] = func(*args, **kwargs)
return cache[(args, kwargs)]
return wraper
@memoize
def slow_function(a, b):
print('Sleeping...')
time.sleep(5)
return a + b
print(slow_function(3,4))
错误:类型错误:不可散列的类型:'dict'
最佳答案
这里有一个简单的方法来避免该问题,即将 kwargs
字典转换为字符串(以及 args
),以生成可接受的字典键。
我从 Memoize 得到了这个想法Python Decorator Library 部分.
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 = {}
def wrapper(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
@memoize
def slow_function(a, b):
print('Sleeping...')
time.sleep(5)
return a + b
print(slow_function(3,4))
关于python - 调用此内存函数会引发 TypeError : unhashable type: 'dict' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64689319/