Comparing Objects
suggest changeIn order to compare the equality of custom classes, you can override == and != by defining __eq__ and __ne__ methods. You can also override __lt__ (<), __le__ (<=), __gt__ (>), and __ge__ (>=). Defining __eq__ is enough for ==. If __ne__ is missing, Python 3 uses the opposite of __eq__. Ordering methods are not filled in for you; functools.total_ordering can supply them from __eq__ and one ordering method. == is not the same thing as not < and not >.
class Foo(object):
def __init__(self, item):
self.my_item = item
def __eq__(self, other):
return self.my_item == other.my_item
a = Foo(5)
b = Foo(5)
a == b # True
a != b # False
a is b # False
Note that this simple comparison assumes that other (the object being compared to) is the same object type. Comparing to another type will throw an error:
class Bar(object):
def __init__(self, item):
self.other_item = item
def __eq__(self, other):
return self.other_item == other.other_item
def __ne__(self, other):
return self.other_item != other.other_item
c = Bar(5)
a == c # AttributeError: 'Bar' object has no attribute 'my_item'
Checking isinstance() or similar will help prevent this (if desired).
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents