__eq__ problem with subclasses

Daniel Israel dmi1 at hushmail.com
Fri Aug 22 16:37:06 EDT 2008


I am very confused by the following behavior.

I have a base class which defines __eq__.  I then have a subclass 
which does not.  When I evaluate the expression a==b, where a and b 
are elements of these classes, __eq__ is always called with the 
subclass as the first argument, regardless of the order I write my 
expression.  I can't see why this would be desired behavior.

A sample code for clarity:

class c1(object):

    def __eq__(self, op):
        print "Calling 
c1.__eq__("+str(type(self))+","+str(type(op))+")"
        return False

class c2(c1):

    pass


a1=c1()
a2=c2()

a1==a2
a2==a1

The output is:

Calling c1.__eq__(<class '__main__.c2'>,<class '__main__.c1'>)
Calling c1.__eq__(<class '__main__.c2'>,<class '__main__.c1'>)

Why does a1==a2 generate a call to c1.__eq__(a2, a1) instead of 
c1.__eq__(a1, e2)?  This is important because I am writing a math 
library in which '==' is being used for assignment, i.e., 'a==b+c' 
set 'a' equal to the sum of 'b' and 'c'.  So 'a==b' is very 
different from 'b==a'.

--
Daniel M. Israel
dmi1 at cornell.edu




More information about the Python-list mailing list