__complex__
特別なメソッドを定義するクラスがあります。私のクラスは標準の数値型 (int、float など) ではありませんが、 、 などに特別なメソッドが定義されているため__add__
、そのように動作します__sub__
。
__complex__
Python が期待する標準の複素数値ではなく、複素数の数値オブジェクトを返したいと思います。そのため、Python は、標準の複素数値ではなく、オブジェクトを返そうとすると次のエラーをスローします。
TypeError: * のサポートされていないオペランド型: 'complex' および 'MyNumericClass'
これを行う最善の方法は何ですか?
編集:
# 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