subclassing complex

Patrick Maupin pmaupin at gmail.com
Fri Aug 29 10:56:57 CEST 2008


On Aug 29, 12:17 am, BiDi <bidih... at gmail.com> wrote:
> I have been trying to subclass complex, but I am not able to get the
> right-hand arithmetic operators working.
>
> As shown below, if an object of my subclass 'xcomplex' is added on the
> right of a 'comlex' object, the type returned is 'complex', not
> 'xcomplex'.
>
> I've tried subclassing float and it works fine (don't even need to
> define __coerce__ in that case)
>
> Is this a bug, or am I missing something?

I think the issue is that Python first tries to use the __add__ method
of the left-most object, and only attempts to use __radd__ with the
right-most object if that fails.  Because you have subclassed the
complex class, the __add__ method of the complex number will work
fine, returning a complex result.

If you want to keep that from working, you probably want to just
inherit from 'object' rather than 'complex', and reimplement all the
methods you care about (possibly with a very simple wrapper around an
internal complex number).

Regards,
Pat



More information about the Python-list mailing list