实现__hash __()的正确和好办法是什么? [英] What's a correct and good way to implement __hash__()?
问题描述
实现 __ hash __()
?
我正在谈论的功能是什么?返回一个哈希码,然后用于将对象插入散列哈希表字典中。
I am talking about the function that returns a hashcode that is then used to insert objects into hashtables aka dictionaries.
As __ hash __()
返回一个整数并且用于将对象binning到散列表中我假定返回的整数的值应该为普通数据均匀分布(以最小化冲突)。
得到这样的价值是什么好习惯?碰撞有问题吗?
在我的情况下,我有一个小类,作为一个容器类,它持有一些int,一些浮点和一个字符串。
As __hash__()
returns an integer and is used for "binning" objects into hashtables I assume that the values of the returned integer should be uniformly distributed for common data (to minimize collisions).
What's a good practice to get such values? Are collisions a problem?
In my case I have a small class which acts as a container class holding some ints, some floats and a string.
推荐答案
实现 __ hash __()
的简单,正确的方法是使用一个关键的元组。它不会像专门的哈希一样快,但如果需要,那么你应该可以在C中实现类型。
An easy, correct way to implement __hash__()
is to use a key tuple. It won't be as fast as a specialized hash, but if you need that then you should probably implement the type in C.
这里是一个使用键的例子哈希和平等:
Here's an example of using a key for hash and equality:
class A(object):
def __key(self):
return (self.attr_a, self.attr_b, self.attr_c)
def __eq__(x, y):
return x.__key() == y.__key()
def __hash__(self):
return hash(self.__key())
此外, __ hash __ $ c的文档$ c>
有更多的信息,这在某些特定情况下可能是有价值的。
Also, the documentation of __hash__
has more information, that may be valuable in some particular circumstances.
这篇关于实现__hash __()的正确和好办法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!