class A(object): def __cmp__(self): print '__cmp__' return object.__cmp__(self) def __eq__(self, rhs): print '__eq__' return True a1 = A() a2 = A() print a1 in set([a1]) print a1 in set([a2])
Why does first line prints True, but second prints False? And neither enters operator eq?
I am using Python 2.6
The equality operator will attempt to make the data types the same before making the comparison. On the other hand, the identity operator requires both data types to be the same as a prerequisite.
The 'is' is known as the identity operator. The == operator helps us compare the equality of objects. The is operator helps us check whether different variables point towards a similar object in the memory. We use the == operator in Python when the values of both the operands are very much equal.
Identity operators are used to compare the memory location of two objects, especially when both the objects have same name and can be differentiated only using its memory location. There are two Identity operators: "is" and "is not" . is - Returns true if both variables are the same object.
The == operator checks to see if two operands are equal by value. The === operator checks to see if two operands are equal by datatype and value.
Set __contains__ makes checks in the following order:
'Match' if hash(a) == hash(b) and (a is b or a==b) else 'No Match'
The relevant C source code is in Objects/setobject.c::set_lookkey() and in Objects/object.c::PyObject_RichCompareBool().
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