On Mon, Nov 17, 2008 at 10:05 AM, Mr. SpOOn <[EMAIL PROTECTED]> wrote: > It seems that I solved my main problem, but I still have some doubt. > > I'll make an example: > >>>> class foo: > ... def __init__(self, a): > ... self.a = a > ... >>>> f = foo(1) >>>> f2 = foo(2) >>>> f3 = foo(3) >>>> f1 = foo(1) >>>> s = set() >>>> s.add(f) >>>> s > set([<__main__.foo instance at 0x8311fac>]) >>>> s.add(f2) >>>> s.add(f3) >>>> s.add(f1) >>>> s > set([<__main__.foo instance at 0x831934c>, <__main__.foo instance at > 0x83191cc>, <__main__.foo instance at 0x8311fac>, <__main__.foo > instance at 0x831932c>]) > > I want that f and f1, that have both self.a set to 1, look the same to > the set, so that it doesn't add f1. In this case the instances looks > all different, so it adds them all. > > I tried rewriting __hash__ and __cmp__ in the foo class, so that > __hash__ simply returns self.a and __cmp__ return self.a == other.a
__cmp__ does rich comparisons and is supposed to return 0 for equality, -1 if the object is less than the other, and 1 if it's greater than the other. So, using == as its definition is broken as it returns just a boolean. You'd want cmp(self.a, other.a) if you were defining __cmp__. However, == obviously works fine for __eq__, hence why switching to __eq__ fixed your problem. Also, __hash__ should probably delegate and be defined as hash(self.a) rather than just self.a itself. > > I thought this would work, but I was wrong. > I had to rewrite __eq__ with the same code of __cmp__ > > Why it doesn't work with __cmp__ or __hash__ ? Probably on account of one of the above errors I explained. Cheers, Chris -- I wonder if there's a Mrs. FoRk... > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list