subclassing complex

BiDi bidihall at gmail.com
Fri Aug 29 01:17:43 EDT 2008


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?

Here's an example:

class xcomplex( complex ):

    def __new__(cls,*args,**kwargs):
        return complex.__new__(cls,*args,**kwargs)

    def __coerce__(self,other):
        t = complex.__coerce__(self,other)
        try:
            return (self,xcomplex(t[1]))
        except TypeError:
            return t

    def __add__(self,x):
        return xcomplex( complex.__add__(self,x) )

    def __radd__(self,x):
        return xcomplex( complex.__radd__(self,x) )


xz = xcomplex(1+2j)
xy = float(10.0)
z = complex(10+1j)

print type(xz + z)  # OK: get xcomplex
print type(xz + xy) # OK: get xcomplex
print type(xz + 10) # OK: get xcomplex
print type(xy + xz) # OK: get xcomplex
print type(10 + xz) # OK: get xcomplex

print type(z + xz)  # fails: get complex



More information about the Python-list mailing list