It's dangerous to write
def __eq__(self, other):
return other and self.a == other.a and self.b == other.b
because if your rhs (i.e., other
) object evaluates to boolean False, it will never compare as equal to anything!
In addition, you might want to double check if other
belongs to the class or subclass of AClass
. If it doesn't, you'll either get exception AttributeError
or a false positive (if the other class happens to have the same-named attributes with matching values). So I would recommend to rewrite __eq__
as:
def __eq__(self, other):
return isinstance(other, self.__class__) and self.a == other.a and self.b == other.b
If by any chance you want an unusually flexible comparison, which compares across unrelated classes as long as attributes match by name, you'd still want to at least avoid AttributeError
and check that other
doesn't have any additional attributes. How you do it depends on the situation (since there's no standard way to find all attributes of an object).