I have a class called IntField
which encapsulates a integer from a database (not really relevant). I'd like to use an instance of IntField
for evaluating expressions using eval
.
The classes looks like:
class DbField(object):
def __init__(self, value):
self.value = value
def __cmp__(self, other):
print "comparing {} ({}) with {} ({})".format(self, type(self), other, type(other))
if type(self.value) == type(other):
return self.value.__cmp__(other)
elif type(self) == type(other):
return self.value.__cmp__(other.value)
raise ValueError("cannot compare {} and {}".format(type(self), type(other)))
class IntField(DbField):
def __init__(self, value):
super(IntField, self).__init__(int(value))
a = IntField(-2)
b = IntField(-2)
print "a=", a
print "b=", b
print "b == -1 ", b == -1
print "b == a ", b == a
print "a == b ", a == b
print "-1 == b ", -1 == b
What I want to achieve in the base class is to allow the custom object to be comparable with another custom object of the same type, but also with the builtin type; I want to be able to do IntField == IntField
or IntField == int
.
I expect that IntField.__cmp__()
of the first object to be called for these comparisons, which is happening. But I'm being puzzled about what happens for int == IntField
. Seems that in this case, the IntField.__cmp__()
method is also being called, instead of int
's . Can someone explain how the comparison against built-in types works?