Problem comparing object graphs and trees
Peter Otten
__peter__ at web.de
Fri Dec 15 09:04:54 EST 2006
raphael.marvie at gmail.com wrote:
> </pre>
> $ cat cmp.py
>
> class A:
> def __init__(self, b):
> self.b = b
> def __cmp__(self, other):
> return self.b == other.b
>
> class B:
> pass
>
> if __name__ == '__main__':
> b = B()
> a1 = A(b)
> a2 = A(b)
> print a1 == a2
> print a1 == a1
>
> $ python cmp.py
> False
> False
> </pre>
>
> I swear I am not drunk, but why isn't a1 == a2 and worse why isn't a1
> == a1? Does someone have a clue and can explain to me this suprising
> behavior? (python 2.4.3 on Ubuntu 6.06).
__cmp__() must return 0 for equal objects:
>>> 1 .__cmp__(0), 1 .__cmp__(1), 1 .__cmp__(2)
(1, 0, -1)
You might have a look at rich comparison before you proceed:
>>> class A(object):
... def __init__(self, b):
... self.b = b
... def __eq__(self, other):
... return self.b == other.b
...
>>> A(1) == A(1)
True
>>> A(1) == A(42)
False
Peter
More information about the Python-list
mailing list