Skip to main content
 首页 » 编程设计

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

2025年05月04日11mfryf

我有 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 在初始分配后永远不会更改。否则你将永远无法从字典中获取对象,因为 data 的 hash 值会有所不同,如果它在稍后的时间点发生变化的话。