__eq__ and __ne__

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Shane Hathaway

    __eq__ and __ne__

    I was surprised by the following behavior. Apparently, the "!="
    operator does not fall back to using "not __eq__()". I tested this with
    Python 2.1, 2.2, and 2.2 with new-style classes and got the same results
    in every case.
    [color=blue][color=green][color=darkred]
    >>> class foo:[/color][/color][/color]
    .... def __eq__(self, other):
    .... return (other.__class_ _ is self.__class__
    .... and other.__dict__ == self.__dict__)
    ....[color=blue][color=green][color=darkred]
    >>> foo() == foo()[/color][/color][/color]
    1[color=blue][color=green][color=darkred]
    >>> foo() != foo()[/color][/color][/color]
    1

    I would expect the second test to yield "0". To compensate, I've
    started adding the following boilerplate code to all classes that define
    only __eq__:

    def __ne__(self, other):
    return not self.__eq__(oth er)

    Does this surprise anyone else? I have not yet found documentation on this.

    Shane


Working...