为我的类在Python 3中创建哈希表

时间:2013-03-20 17:40:04

标签: python dictionary

我创建了一个包含多个成员的类。

我想创建哈希表,包含此类的“对象”并能够搜索(使用hashmap :))

据我所知,我应该重载__eq__运算符

我应该从那里开始?

我无法找到任何在python中创建哈希表的引用...尤其不适用于“我的班级”

1 个答案:

答案 0 :(得分:5)

您需要实施.__hash__() method以及.__eq__()方法。

该方法应该返回一个整数,对于.__eq__()返回True的任何两个对象,.__hash__() 必须返回相同的整数值。

实现此目的的最简单方法是在实例的每个属性上使用内置hash() function使其唯一,并返回这些值的XORed结果。

示例:

class Foo(object):
    def __init__(self, bar, baz):
        self.bar = bar
        self.baz = baz

    def __eq__(self, other):
        if isinstance(other, type(self)):
            return self.bar == other.bar and self.baz == other.baz
        return False

    def __hash__(self):
        return hash(self.bar) ^ hash(self.baz)

演示:

>>> foo1 = Foo('ham', 'eggs')
>>> foo2 = Foo('ham', 'eggs')
>>> foo3 = Foo('spam', 'vikings')
>>> foo1 == foo2
True
>>> foo1 == foo3
False
>>> hash(foo1)
1838536788654183919
>>> hash(foo1) == hash(foo2)
True
>>> hash(foo1) == hash(foo3)
False
>>> mapping = {}
>>> mapping[foo1] = 'Monty Python'
>>> foo1 in mapping
True
>>> foo2 in mapping
True
>>> foo3 in mapping
False
>>> mapping[foo2]
'Monty Python'