Prashant Kumar Prashant Kumar - 1 year ago 153
Python Question

overriding __cmp__ python function

Hi I am overriding

. If the second object passed is
, or if it is not an instance of
, then it returns

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
    when the comparison signs are changed?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download