Reputation: 549
I have a python class declared like the following within a module
class Position:
def __init__(self, x, y):
self.x = int(x)
self.y = int(y)
def __str__(self):
return self.toString()
def toString(self): #deprecated
return "{x:"+str(self.x)+" y:"+str(self.y)+"}"
Now, later in the main program, I do a comparation like this:
can_pos = somestreet.endOfStreet(curPos).getPos() #returns a Position object
if(can_pos == atPos): # this returns False
#blafoo
#if(can_pos.x == atPos.x and can_pos.y == atPos.y): #this returns True (and is expected)
I do not understand what the reason for the different behaviour could be ...
It would be very nice if someone could give me a hint on that :)
Thanks in advance
Upvotes: 0
Views: 191
Reputation: 353059
As noted in the comments, you need to define at least __eq__
and __ne__
explicitly:
class Position:
def __init__(self, x, y):
self.x = int(x)
self.y = int(y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __ne__(self, other):
return not self == other
which gives
>>> a = Position(1,2)
>>> b = Position(1,2)
>>> c = Position(2,3)
>>> a == b
True
>>> a == c
False
>>> b == c
False
>>> a != a
False
>>> a != b
False
>>> a != c
True
Note, however, than in Python 2, you'll have:
>>> a > c
True
and other possibly undesirable behaviours, whereas in Python 3 (which you're using) you'll get
TypeError: unorderable types: Position() > Position()
Upvotes: 3