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:
True or False when the comparison signs are changed?The convention for __cmp__ is:
a < b : return -1
a = b : return 0
a > b : return 1
This of course makes only sense if both a and b are of compatible types, say numbers. If you have a 'corner case', where a or b is either None or incompatible (not instanceof), you should report an error, as this is a programming error in the use of the comparison operators on your someClass instance.
It is possible to implement any behaviour with __cmp__, but a comparison with None the way described by the OP will eventually lead to strange behaviour and bugs.
see also: __lt__ instead of __cmp__
http://docs.python.org/reference/datamodel.html#object.__cmp__
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With