Get item from set
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Sun Apr 26 09:21:21 EDT 2009
Peter Otten:
> [...] I think Raymond Hettinger posted
> an implementation of this idea recently, but I can't find it at the moment.
> [...]
> class Grab:
> def __init__(self, value):
> self.search_value = value
> def __hash__(self):
> return hash(self.search_value)
> def __eq__(self, other):
> if self.search_value == other:
> self.actual_value = other
> return True
> return False
>
> assert a == z
> assert a is not z
> grab = Grab(z)
> grab in s
> assert grab.actual_value is a
That's very nice, and I may add to my tricks. Probably Raymond has
more brain than me :-)
But some other times you may accept to change the class and the set/
dict, making it tell apart the keys only when they are different
object:
class Some(object):
def __init__(self, y):
self._y = y
def __eq__(self, other):
return self is other
def __hash__(self):
return hash(self._y)
Now your set/dict keeps all the instances, even when they contain the
same _y.
Bye,
bearophile
More information about the Python-list
mailing list