我有一个定义__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
答案 0 :(得分:3)
有两种选择:
__rmul__
(或定义__mul__
并翻转乘法操作数。)MyNumericClass
实例投射到complex
。