Which class's comparison function is called?

Basilisk96 basilisk96 at gmail.com
Tue Jun 5 23:15:28 EDT 2007


Try adding the following diagnostic messages to your __eq__ class
definitions, and see if it will dispel the confusion for the four
equality tests you have tried:

 class A:
    def __init__(self,a):
      self.a = a
    def __eq__(self, other):
      print "(A) self:%r, other:%r" %(self.__class__, other.__class__)
      return self.a == other.a

 class B:
    def __init__(self,b):
      self.b = b
    def __eq__(self, other):
      print "(B) self:%r, other:%r" %(self.__class__, other.__class__)
      return self.b == other.b

You are correct, Python evaluates the expressions from left to right.

> A(1) == B(1)
> ---> AttributeError: B instance has no attribute a

The left instance's __eq__ method is invoked, which says, "is the
value of self.a equal to the value of other.a ?"; and the answer is,
"other has no attribute a to compare with self.a!" so you get an
exception.


> B(1) == A(1)
> ---> AttributeError: A instance has no attribute b

Same case as the first, but the instances have switched places...


> A(1) == 3
> ---> AttributeError: 'int' object has no attribute a

Same case as the first, but 'other' is now an object of type 'int',
which inherently has no attribute 'a'. A similar effect will manifest
when you will try to do:
B(1) == 3
---> AttributeError: 'int' object has no attribute 'b'

> 3 == A(1)
> ---> AttributeError: 'int' object has no attribute a
>
> Can someone explain this?  I expected 3 == A(1) to use the __eq__
> function defined for 'int' objects.

This last one is interesting.
The '__eq__' method is not defined for 'int' objects.  The '=='
operator tests for value equivalence. As before, the left side is
evaluated first, and evaluates to a simple integer value. No special
methods are called. Now, the right side's value is evaluated.  Since
equality is being tested, the right side's __eq__ method is called,
with the (self, other) arguments being (<instance of class A>, 3)
respectively. Since 'int' is the 'other' argument in this case, it
again results in the exception "no attribute 'a' ".


The last of the four tests that you have mentioned is giving you the
trouble, right? Perhaps the solution is to add type-checking to the
__eq__ method?

(untested)
def __eq__(self, other):
  if isinstance(other, int):
    tmp = other
  else:
    tmp = other.a   # (other.b in class B definition)
  return self.a == tmp   # (self.b in class B definition)

Cheers,
-Basilisk96




More information about the Python-list mailing list