tby tby - 2 months ago 13
Python Question

how to compare two objects in class using __cmp__ method in Python?

class Box(object):
def __init__(self, ival):
self.value = ival
def __cmp__(self,other):
if self.value < other:
return
elif self.value > other:
return 1
else:return 0


But when I wanna test the program with :

Box(2) < Box(2)
Box(2) <= Box(2)
Box(1) >= Box(2)
Box(3) > Box(2)
Box(0) == Box(1)
Box(0) != Box(0)


Part of the code below:

Box(1) >= Box(2)
Box(3) > Box(2)
Box(0) == Box(1)


has shown


TypeError: an integer is required


Anyone knows why?

EDITED :I added the -1 before but somehow I deleted it -.-
sorry for asking such careless question!

Answer

You have to compare self.value to other.value:

def __cmp__(self,other):
    if self.value < other.value:
        return -1
    elif self.value > other.value:
        return 1
    else:return 0

otherwise you're comparing an integer to an object