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.
python comparison set methods
Ada Oct. 15 2018-10-15 12:42
source share