I want to use sets on some classes I've made. I want those sets to restrict the multiplicity of my objects of that class. However I have a problem. Consider this toy example:
class Thing(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
def __repr__(self):
return str(self.value)
a = Thing(5)
b = Thing(5)
s = set()
s.add(a)
s.add(b)
print s
The output of 开发者_StackOverflow中文版this code is:
set([5, 5])
I just assumed that set() would use __eq__
to determine whether the object should be included, but perhaps it uses is
. Is there an easy workaround such that the output would just be set([5])
?
You need to define the __hash__
method of your class to return a hashcode based on value
.
In other words, you need to make your class hashable.
class Thing(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
def __repr__(self):
return str(self.value)
def __hash__(self):
return hash(self.value)
a = Thing(5)
b = Thing(5)
s = set()
s.add(a)
s.add(b)
print s
精彩评论