Attribute Error: Rich Comparison Configuration

I have a Point class with x and y attributes. I would like to get a False comparison of a Point object with any other type of object. For example, Point(0, 1) == None does not work:

 AttributeError: 'NoneType' object has no attribute 'x' 

Grade:

 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 compared to any other type of object?

+4
source share
3 answers
 def __eq__(self, other): if not isinstance(other, Point): return False try: return self.x == other.x and self.y == other.y except AttributeError: return False 

First check the type and return False if it is not a Point instance. We do this if they compare another type that has the x or y attribute, but not necessarily the same context.

The second is catching an attribute error, just in case someone subclasses Point and removes the attribute or changes the point in some way.

+1
source

I would see if another object would act like a Point object instead of rejecting all non Point objects:

 def __eq__(self, other): try: return self.x == other.x and self.y == other.y except AttributeError: return False 

So Point(1, 1) == Vector(1, 1) if you use coordinate vectors.

+2
source

Try the following:

 def __eq__(self, other): return isinstance(other, Point) and self.x == other.x and self.y == other.y 
+1
source

All Articles