Note that there are some explanatory texts on larger screens.

plurals
  1. POComparison of object with built-in type
    primarykey
    data
    text
    <p>I have a class called <code>IntField</code> which encapsulates a integer from a database (not really relevant). I'd like to use an instance of <code>IntField</code> for evaluating expressions using <code>eval</code>. </p> <p>The classes looks like:</p> <pre><code>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 </code></pre> <p>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 <code>IntField == IntField</code> or <code>IntField == int</code>. </p> <p>I expect that <code>IntField.__cmp__()</code> of the first object to be called for these comparisons, which is happening. But I'm being puzzled about what happens for <code>int == IntField</code>. Seems that in this case, the <code>IntField.__cmp__()</code> method is also being called, instead of <code>int</code>'s . Can someone explain how the comparison against built-in types works? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload