I need to create a \'container\' object or class in Python, which keeps a record of other objects which I also define. One requirement of this container is that if two objec
Yes, you need a __hash__()
-method AND the comparing-operator which you already provided.
class Item(object):
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
def __repr__(self):
return "Item(%s, %s)" % (self.foo, self.bar)
def __eq__(self, other):
if isinstance(other, Item):
return ((self.foo == other.foo) and (self.bar == other.bar))
else:
return False
def __ne__(self, other):
return (not self.__eq__(other))
def __hash__(self):
return hash(self.__repr__())
I am afraid you will have to provide a __hash__()
method. But you can code it the way, that it does not depend on the mutable attributes of your Item
.