Differences of "!=" operator behavior in python3 and python2 [ bug? ]
Christian Heimes
christian at python.org
Sun May 12 19:39:03 EDT 2013
Am 13.05.2013 01:23, schrieb Mr. Joe:
> I seem to stumble upon a situation where "!=" operator misbehaves in
> python2.x. Not sure if it's my misunderstanding or a bug in python
> implementation. Here's a demo code to reproduce the behavior -
> """
Python 2.7 doesn't use the negation of __eq__ when your class doesn't
provide a __ne__ function. Just add a print() to your __eq__ method and
you'll notice the different.
You have to provide both:
class DemoClass(object):
def __init__(self, val):
self.val = val
def __eq__(self, other):
if not isinstance(other, DemoClass):
return NotImplemented
return self.val == other.val
def __ne__(self, other):
if not isinstance(other, DemoClass):
return NotImplemented
return self.val != other.val
or
def __ne__(self, other):
result = self.__eq__(other)
if result is NotImplemented:
return NotImplemented
return not result
More information about the Python-list
mailing list