how to compare two objects in class using __cmp__ method in Python?
<pre><code>class Box(object):
def __init__(self, ival):
    self.value = ival
def __cmp__(self,other):
    if self.value &lt; other:
        return 
    elif self.value &gt; other:
        return 1
    else:return 0
</code></pre>

<p>But when I wanna test the program with :</p>

<pre><code>Box(2) &lt; Box(2)
Box(2) &lt;= Box(2)
Box(1) &gt;= Box(2)
Box(3) &gt; Box(2)
Box(0) == Box(1)
Box(0) != Box(0)
</code></pre>

<p>Part of the code below:</p>

<pre><code>Box(1) &gt;= Box(2)
Box(3) &gt; Box(2)
Box(0) == Box(1)
</code></pre>

<p>has shown </p>

<blockquote>
  <p>TypeError: an integer is required</p>
</blockquote>

<p>Anyone knows why?</p>

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

<p>Python's __cmp__ magic method returns an integer > 0 if greater, 0 if equal, and &lt; 0 if less. You can see that in the <a href="https://docs.python.org/2/reference/datamodel.html#object.__cmp__" rel="nofollow">docs</a>.</p>

<p>Your __cmp__ function returns None for the 'less than' comparison.</p>

<pre><code>class Box(object):
    def __init__(self, ival):
        self.value = ival
    def __cmp__(self,other):
        if self.value &lt; other:
            return   # return None   &lt;--------- bad
        elif self.value &gt; other:
            return 1
        else:return 0
</code></pre>

<p>It should be:</p>

<pre><code>class Box(object):
    def __init__(self, ival):
        self.value = ival
    def __cmp__(self,other):
        if self.value &lt; other:
            return -1  # &lt;--------- yay!
        elif self.value &gt; other:
            return 1
        else:
            return 0
</code></pre>

<p>As others pointed out, if you are seeking to compare a Box to another Box, you should modify your __cmp__ method to compare <code>other.value</code>, not just <code>other</code>.</p>

<pre><code>class Box(object):
    def __init__(self, ival):
        self.value = ival
    def __cmp__(self,other):
        if self.value &lt; other.value:
            return -1
        elif self.value &gt; other.value:
            return 1
        else:
            return 0
</code></pre>

python python-2.7