On 5/12/2013 7:23 PM, Mr. Joe wrote:
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 - """ # -*- coding: utf-8 -*- from __future__ import unicode_literals, print_functionclass DemoClass(object): def __init__(self, val): self.val = val def __eq__(self, other): return self.val == other.val x = DemoClass('a') y = DemoClass('a') print("x == y: {0}".format(x == y)) print("x != y: {0}".format(x != y)) print("not x == y: {0}".format(not x == y)) """ In python3, the output is as expected: """ x == y: True x != y: False not x == y: False """
In Python 3, if __ne__ isn't defined, "!=" will call __eq__ and negate the result.
In python2.7.3, the output is: """ x == y: True x != y: True not x == y: False """ Which is not correct!!
In Python 2, "!=" only calls __ne__. Since you don't have one defined, it's using the built-in object comparison, and since x and y are different objects, they are not equal to each other, so x != y is True.
Thanks in advance for clarifications. Regards, TB
-- http://mail.python.org/mailman/listinfo/python-list
