python - 为字典实现自定义键,以便同一类的 2 个实例匹配

标签 python python-3.x dictionary hash

我有 2 个类的实例,我想将它们解析为字典中的同一个键:

class CustomClass(): 
    def __hash__(self):
        return 2

a = CustomClass()        
b = CustomClass()        

dicty = {a : 1}

这里,a 和 b 作为键不相等:

>>> a in dicty
True
>>> b in dicty
False

哈希究竟发生了什么;似乎 CustomClass 的第二个实例应该匹配散列?这些哈希值不匹配是怎么回事?

我刚刚发现真正的类是被散列的。那么如何为类添加自定义字典键(即,当我尝试将类用作字典的键时,应如何存储它以便 a 和 b 匹配)?

请注意,在这种情况下,我不关心在字典中保留指向原始对象的链接,我可以使用一些不可用的关键对象;重要的是他们做出相同的决定。

编辑:

也许需要一些关于我想解决的实际案例的建议。

我的类包含形状为 (8,6) 的 bool 值 np.arrays。我想对这些进行哈希处理,以便每当将此对象放入字典时,都会对这些值进行比较。我根据 this 用它们制作了一个位数组回答。我注意到那里有一个 __cmp__(感谢 thefourtheye 显示我必须看那里)。但是,我的类可以更新,所以我只想在我实际尝试将它放入字典时散列 np.array,而不是在启动时散列(因此在我 init 时存储可散列的位数组,因为 np.array 可能会更新,因此散列不再是真实的表示形式)。我知道每当我更新 np.array 时,我也可以更新散列值,但我宁愿只散列一次!

最佳答案

您违反了 __hash____cmp____eq__ 之间的约定。引用 __hash__ documentation ,

If a class does not define a __cmp__() or __eq__() method it should not define a __hash__() operation either; if it defines __cmp__() or __eq__() but not __hash__(), its instances will not be usable in hashed collections. If a class defines mutable objects and implements a __cmp__() or __eq__() method, it should not implement __hash__(), since hashable collection implementations require that a object’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).

User-defined classes have __cmp__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y).

在您的例子中,两个对象的散列值相同,hash Collision在任何哈希实现中都很常见。所以,Python 将查找的对象与帮助__eq__ 方法进行比较,发现实际查找的对象与已经存储的对象不一样。这就是为什么b in dicty 返回 False

因此,要解决您的问题,还需要像这样定义自定义 __eq__ 函数

class CustomClass():

    def __init__(self):
        self.data = <something>

    def __hash__(self):
        # Find hash value based on the `data`
        return hash(self.data)

    def __eq__(self, other):
        return self.data == other.data

注意: __hash__ 值对于给定对象应该始终相同。因此,请确保 data 在初始分配后永远不会更改。否则你将永远无法从字典中获取对象,因为 datahash 值会有所不同,如果它在稍后的时间点发生变化的话。

关于python - 为字典实现自定义键,以便同一类的 2 个实例匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28644265/

相关文章:

python - 从字符串中获取数字

python - 为什么 bool 是 Python 3 中 int 的子类?

python - bisect_left 在列表中列表的第一项上,Python 3

python - 为什么 mouseMoveEvent 在 PyQt5 中什么都不做

arrays - 如何编写一个接受字符串输入并打印该字符串中第一个重复次数最多的字符的方法

python - python字典中没有值

iphone - 如何从 google api 调用获取单个目的地的多条距离路线结果?

python - 如何使用 docker-compose 设置一个容器以允许其整个卷访问另一个容器

python - Groupby 并使用 Vaex 组合数据框

python - 使用 Python 将字符串解析为重叠对