Take the following example:
>>> class C(object):
... def __init__(self, p):
... self.p = p
... def __eq__(self, o):
... return True
...
>>> C(1) is C(2)
False
>>> C(1) == C(2)
True
>>> C(1) != C(2)
True # <- Why?!?
So now the two objects are equal and not-equal at the same time. I though the two operations are opposing?!
You can use "!= " and "is not" for not equal operation in Python. The python != ( not equal operator ) return True, if the values of the two Python operands given on each side of the operator are not equal, otherwise false .
Variables with the same value are often stored at separate memory addresses. This means that you should use == and != to compare their values and use the Python is and is not operators only when you want to check whether two variables point to the same memory address.
Difference between == and = in Python. In Python and many other programming languages, a single equal mark is used to assign a value to a variable, whereas two consecutive equal marks is used to check whether 2 expressions give the same value . (x==y) is False because we assigned different values to x and y.
Python’s “Data model” explains it all:
There are no implied relationships among the comparison operators. The truth of
x==y
does not imply thatx!=y
is false. Accordingly, when defining__eq__()
, one should also define__ne__()
so that the operators will behave as expected.
In C(1) != C(2)
, it’s using the default implementation, where objects are equal only to themselves and unequal to everything else.
Defining __cmp__
can be simpler, as it is used as a fallback for all comparison operations, not just some of them:
... def __cmp__(self, o):
... return 0
>>> C(1) != C(2)
False
There is a separate function for !=
which is __ne__
which is implicitly defined to compare the instance members.
What you want to do is:
def __ne__(self, other):
return not self.__eq__(other)
or some variant of this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With