I noticed I can use the ==
operator to compare all the native data types (integers, strings, booleans, floating point numbers etc) and also lists, tuples, sets and dictionaries which contain native data types. In these cases the ==
operator checks if two objects are equal. But in some other cases (trying to compare instances of classes I created) the ==
operator just checks if the two variables reference the same object (so in these cases the ==
operator is equivalent to the is
operator)
My question is: When does the ==
operator do more than just comparing identities?
EDIT: I'm using Python 3
In Python !=is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal.
The is operator compares the identity of two objects while the == operator compares the values of two objects. There is a difference in meaning between equal and identical. And this difference is important when you want to understand how Python's is and == comparison operators behave.
The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .
In Python, the ==
operator is implemented in terms of the magic method __eq__
, which by default implements it by identity comparison. You can, however, override the method in order to provide your own concept of object equality. Note, that if you do so, you will usually also override at least __ne__
(which implements the !=
operator) and __hash__
, which computes a hash code for the instance.
I found it very helpful, even in Python, to make my __eq__
implementations comply with the rules set out in the Java language for implementations of the equals
method, namely:
the last one should probably replace null
with None
, but the rules are not as easy here in Python as in Java.
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