Customizing sequence types

Mr.SpOOn mr.spoon21 at gmail.com
Mon Nov 17 13:05:52 EST 2008


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

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__ ?



More information about the Python-list mailing list