Reputation: 215
Python provides the feature of overloading ==
operator AND !=
operator. But, why? Isn't it enough to overload ==
and !=
is automatically the opposite (in truth value) of ==
?
Shouldn't the result of one imply the other automatically?
Upvotes: 2
Views: 270
Reputation: 402892
You don't have to, python isn't forcing you to. In fact, the documentation explains the what and why:
By default,
__ne__()
delegates to__eq__()
and inverts the result unless it isNotImplemented
. There are no other implied relationships among the comparison operators, for example, the truth of (x<y
orx==y
) does not implyx<=y
.
In general, the truth of x==y
does not have need to imply that x!=y
is false. If your data model needs to reflect this relationship, python lets you do so with minimal headache.
Note that for earlier versions of python, not even this relationship was implied. For example,
class Foo:
def __init__(self, val):
self.val = val
def __eq__(self, other):
return self.val == other.val
f1, f2 = Foo(1), Foo(1)
Now, f1 == f2
returns True
on any version. HOWEVER, f1 != f2
returns False
on python-3.x, but True
on python-2.x (because __ne__
is not implied on python-2.x, and in general two user defined objects are not equal if their IDs are not the same, i.e., not the same object).
Upvotes: 6