I have a class Point with xand y attributes. I’d like to get False comparing a Point object with any other type of object. For instance, Point(0, 1) == None fails:
AttributeError: 'NoneType' object has no attribute 'x'
The class:
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __ne__(self, other):
return not self.__eq__(other)
How do I configure __eq__to get False in comparison with any other object type?
First check the type and return False if its not a Point instance. We do this in case they are comparing some other type that happens to have an
xoryattribute but isn’t necessarily the same context.Second catch an attribute error, just in case someone subclasses Point and removes the attribute or changes Point in some way.