Which class's comparison function is called?

Bill Jackson jackson at hotmail.com
Wed Jun 6 04:16:53 CEST 2007

For example,

class A:
   def __init__(self,a):
     self.a = a
   def __eq__(self, other):
     return self.a == other.a

class B:
   def __init__(self,b):
     self.b = b
   def __eq__(self, other):
     return self.b == other.b

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

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

 From the above, it seems that Python always uses the function defined 
by the class on the LEFT.  However, I don't understand the following then:

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

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.

More information about the Python-list mailing list