On Fri, 23 Jul 2010 09:22:55 pm m...@doctors.net.uk wrote: > Dear Tutors, > > I am tring to deal with some repeated data, and hence repeated > objects (I construct objects from the data). > > I had hoped to use a set to uniquify the objects. However, I am > having problems with defining uniqueness.
The objects need to define __eq__ and __hash__, and they must be immutable. The easy way to do so is to inherit from something which is already immutable, say strings, ints, tuples or floats: class MyObject(int): """Just like an int, but coloured purple.""" def __init__(self, *args): self.colour = 'purple' Otherwise, something like this recipe should do the job: class MyObject(object): def __init__(self, a, b): self._value = (a, b) # Private attribute, don't touch this. @property def value(self): return self._value def __eq__(self, other): if isinstance(other, MyObject): return self.value == other.value return NotImplemented # Let the other object try. def __ne__(self, other): return not self == other def __hash__(self): return hash(self.value) If x and y are instances of your class, and x equals y, then hash(x) *must* equal hash(y). (The opposite doesn't apply though... if x and y hash equal, they don't necessarily have to equal.) -- Steven D'Aprano _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor