python 2 and python 3 __cmp__ -
when use code in python 2 works fine while python 3 gives me error
class point: def __init__(self,x,y): self.x=x self.y=y def dispc(self): return ('(' +str(self.x)+','+str(self.y)+')') def __cmp__(self,other): return ((self.x > other.x) , (self.y > other.y)) ....................................................................
shubham@shubham-vpcea46fg:~/documents/programs$ python3 -i classes.py >>> p=point(2,3) >>> q=point(3,4) >>> p>q traceback (most recent call last): file "<stdin>", line 1, in <module> typeerror: unorderable types: point() > point() >>> shubham@shubham-vpcea46fg:~/documents/programs$ python -i classes.py >>> p=point(2,3) >>> q=point(3,4) >>> p>q false >>> ...................................................................
in python 3 gives error on and while works == , !=.
please suggest solution.
you need provide __lt__ , __eq__ method ordering in python 3. __cmp__ no longer used.
updated respond questions/comments below
__lt__ takes self , other arguments, , needs return whether self less other. example:
class point(object): ... def __lt__(self, other): return ((self.x < other.x) , (self.y < other.y)) so if have following situation:
p1 = point(1, 2) p2 = point(3, 4) p1 < p2 this equivalent to:
p1.__lt__(p2) which return true. __eq__ return true if points equal , false otherwise. if use functools.total_ordering decorator recommended below, need provide __lt__ , __eq__:
from functools import total_ordering @total_ordering class point(object): def __lt__(self, other): ... def __eq__(self, other): ...
Comments
Post a Comment