On Oct 16, 2009, at 2:24 AM, [email protected] wrote:

> I've just been struggling with understanding how inheritance and
> __richcmp__ are related.  Here is my example code:
>
> cdef class A:
>    cdef int a
>    def __init__(self, a):
>        self.a=a
>
>    def __hash__(self):
>        return self.a
>
>    def __richcmp__(A self, A other, int op):
>        print "using op: ",op
>        if op == 2: # ==
>            return self.a == other.a
>
> cdef class B(A):
>    def __init__(self, a):
>        self.a=a+1
>
>    def __hash__(self):
>        return self.a*2
>
>
> Mike Hansen found some reference somewhere that said that either all  
> of
> __hash__, __richcmp__, and __cmp__ are inherited or none are (I didn't
> see this in the manual, but maybe I was looking in the wrong place??).

This is in the Python/C API docs.

> So, predictably:
>
> sage: A(2)==A(2)
> using op:  2
> True
> sage: B(2)==B(2)
> False
>
> However, the confusing part is this:
>
> sage: B(2).__eq__(B(2))
> using op:  2
> True
>
>
>
>
> Also, unlike most other special methods, I noticed that if I defined
> __richcmp__ as below (removing the type declaration for self):
>
>    def __richcmp__(self, A other, int op):
>        print "using op: ",op
>        if op == 2: # ==
>            return self.a == other.a
>
> then self can't access the cdef'd "a" attribute.  I think most other
> commands recognize that self is of type A.  That took a bit to figure
> out, and I don't remember that being in the Cython docs either.

That is because "self" may be either the first or second operand. It's  
the same with __add__, etc. (there's no __radd__). This does need to  
be better documented--in fact the documentation is being overhauled  
right now.

- Robert

_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to