How does the Python set ([]) check if two objects match? What methods should an object define to configure it?

I need to create an object or container class in Python that stores a record of other objects that I also define. One of the requirements of this container is that if two objects are considered identical, one (one) is deleted. My first thought was to use set([]) as the containing object to fulfill this requirement.

However, the collection does not delete one of two identical instances of the object. What should I define to create it?

Here is the Python code.

 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)) 

Translator

 >>> set([Item(1,2), Item(1,2)]) set([Item(1, 2), Item(1, 2)]) 

Clearly, __eq__() , which is called by x == y , is not a method called by the set. What is caused? What other method should I define?

Note. Item s must remain volatile and subject to change, so I cannot provide the __hash__() method. If this is the only way to do this, I will rewrite to use immutable Item s.

+54
python comparison set methods
Oct. 15 2018-10-15
source share
2 answers

I am afraid you will have to provide the __hash__() method. But you can encode it so that it does not depend on the mutable attributes of your Item .

+21
Oct. 15 2018-10-15
source share

Yes, you need the __hash__() method AND the comparison operator that 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__()) 
+47
Jun 25 '13 at 16:31
source share



All Articles