Prashant Kumar Prashant Kumar - 2 months ago 13
Python Question

overriding __cmp__ python function

Hi I am overriding

__cmp__
. If the second object passed is
None
, or if it is not an instance of
someClass
, then it returns
-1
.

I don't understand what exactly is happening here.

class someClass():
def __cmp__(self, obj):
if obj == None:
return -1
if not isinstance(obj, someClass):
return -1


My test function:

def test_function(self):
obj1 = someClass()
self.assertTrue(obj1 < None)
# I get true.
self.assertTrue(obj1 > None)
# I get failure as False is returned.


Could anyone please explain to me:


  • What are the return values?

  • How is it deciding whether it will return
    True
    or
    False
    when the comparison signs are changed?


Answer

When the obj is None, your program will return -1, while returning a negative integer means self < obj, so obj1 < None is True, and obj1 > None is false.

Comments