Customizing sequence types

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Nov 17 19:59:40 EST 2008


En Mon, 17 Nov 2008 22:04:43 -0200, Mr.SpOOn <mr.spoon21 at gmail.com>  
escribió:

> On Mon, Nov 17, 2008 at 8:30 PM, Terry Reedy <tjreedy at udel.edu> wrote:
>> Sets and dicts use __hash__ and __eq__ together, as documented.
>>
>> "If a class does not define an __eq__() method it should not define a
>> __hash__() operation either;" (3.0 manual, but same earlier).
>
> Well, maybe, but in the docs, for the __hash__ method I read:
>
> "If a class does not define a __cmp__() method it should not define a
> __hash__() operation either;"
>
>> From here: http://www.python.org/doc/2.5.2/ref/customization.html

Yes, __cmp__ is gone in 3.0
You said you wrote __cmp__ the same as __eq__ and that's wrong, they  
return different results. Try something like this (untested):

class X:
   def __init__(self, a): self.a = a
   def __cmp__(self, other): return cmp(self.a, other.a)
   def __hash__(self): return hash(self.a)

x1 = X(1)
x2 = X(2)
x3 = X(3)
x4 = X(1)

print len(set([x1, x2, x3, x4]) # should be 3!

-- 
Gabriel Genellina




More information about the Python-list mailing list