python - 如果来自 Python 字典的子类,则 LRU 缓存不可散列的类型
问题描述
我试图弄清楚为什么以下代码不起作用
from functools import lru_cache
import numpy as np
class Mask(dict):
def __init__(self, shape, data = None):
super().__init__(data)
self.shape = shape
@lru_cache(maxsize=1)
def tomatrix(self):
dense = np.zeros(self.shape[0] * self.shape[1])
for uid, entries in self.items():
dense[entries] = uid
return np.reshape(dense, self.shape)
cells = {i : np.arange(i * 10, (i + 1) * 10) for i in range(10)}
mask = Mask((10, 10), cells)
r1 = mask.tomatrix()
r2 = mask.tomatrix()
错误说
TypeError: unhashable type: 'Mask'
好像lru_cache
试图缓存self
在self.tomatrix()
.
另一方面,如果我没有从子类dict
化,而是有一个存储实际数据的内部成员self.data
,LRU 包装器不会抱怨。
有效的代码:
from functools import lru_cache
import numpy as np
class Mask:
def __init__(self, shape, data = None):
self.data = data
self.shape = shape
@lru_cache(maxsize=1)
def tomatrix(self):
dense = np.zeros(self.shape[0] * self.shape[1])
for uid, entries in self.data.items():
dense[entries] = uid
return np.reshape(dense, self.shape)
cells = {i : np.arange(i * 10, (i + 1) * 10) for i in range(10)}
mask = Mask((10, 10), cells)
r1 = mask.tomatrix()
r2 = mask.tomatrix()
谁能帮我解开这个谜?我想继续子类化dict
,我需要使用 LRU 缓存。
解决方案
解决方案是获取__hash__
为继承自的用户类定义的默认函数object
。dict
定义了它自己的__eq__
,但没有__hash__
因此被阻止。
添加行
__hash__ = object.__hash__
工作Mask(dict)
。
非常感谢对另一个问题的回答!
推荐阅读
- python - Python搜索多个值存在于列表列表中
- c# - Preventing access to base method from derived class
- python - 需要登录时如何从网站上抓取数据?
- c# - 如何在 C# System.Drawing.Font 中使用 Helvetica 和 Helvetica Black?
- swift - 从 Struct 中的 FirebaseStorage 获取数据
- java - moveCamera() 在 Android 上使用了错误的位置数据
- if-statement - 为什么这种语法会在“else”子句中产生错误?
- jestjs - 如何测试在玩笑中使用 `requestAnimationFrame` 的代码?
- ios - 使用 Apple 登录 - 隐藏电子邮件
- android - 关于 DatePickerDialog 使用 DialogFragment 的几个问题