我创建了一个包含几个成员的类.
我想创建哈希表,包含此类的"对象"并能够搜索(使用hashmap :))
据我所知,我应该超载__eq__操作员
我该怎么走?
我无法找到任何在python中创建哈希表的引用...尤其不适用于"我的班级"
您需要实现该.__hash__()方法以及.__eq__()方法.
该方法应返回的整数,并且对于任何两个对象,其中.__eq__()返回True,.__hash__() 必须返回相同的整数值.
实现此目的的最简单方法是在实例的每个属性上使用内置hash()函数使其唯一,并返回这些值的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)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> 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'
Run Code Online (Sandbox Code Playgroud)