I have a class that defines the __complex__ special method. My class is not a standard numeric type (int, float, etc.), but it behaves like one as I have special methods defined for __add__, __sub__, etc.
I would like __complex__ to return my complex valued numeric object, not a standard complex numeric value python expects. As such, Python throws the following error when I try to return my object, rather than a standard complex numeric.
TypeError: unsupported operand type(s) for *: ‘complex’ and
‘MyNumericClass’
What’s the best way to do this?
Edit:
# Python builtins
import copy
# Numeric python
import numpy as np
class MyNumericClass (object):
""" My numeric class, with one single attribute """
def __init__(self, value):
self._value = value
def __complex__(self):
""" Return complex value """
# This looks silly, but my actual class has many attributes other
# than this one value.
self._value = complex(self._value)
return self
def zeros(shape):
"""
Create an array of zeros of my numeric class
Keyword arguments:
shape -- Shape of desired array
"""
try:
iter(shape)
except TypeError, te:
shape = [shape]
zero = MyNumericClass(0.)
return fill(shape, zero)
def fill(shape, value):
"""
Fill an array of specified type with a constant value
Keyword arguments:
shape -- Shape of desired array
value -- Object to initialize the array with
"""
try:
iter(shape)
except TypeError, te:
shape = [shape]
result = value
for i in reversed(shape):
result = [copy.deepcopy(result) for j in range(i)]
return np.array(result)
if __name__ == '__main__':
a_cplx = np.zeros(3).astype(complex)
print a_cplx
b_cplx = zeros(3).astype(complex)
print b_cplx
A couple of options:
__rmul__(or define__mul__and flip the multiplication operands).MyNumericClassinstance tocomplexbefore multiplying.