我有一個類定義了__complex__
特殊方法。我的階級是不是一個標準的數字類型(整型,浮點等),但它的行爲就像一個我已經爲__add__
,__sub__
定義的特殊方法等類特殊方法行爲__complex__
我想__complex__
回到我的復值的數字對象,而不是python期望的標準複雜數值。因此,當我嘗試返回我的對象時,Python會拋出以下錯誤,而不是標準的複數數字。
TypeError: unsupported operand type(s) for *: 'complex' and '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
在沒有看到代碼的情況下猜測問題可能會有點困難。你定義了__rmul __()嗎? –
完成。請參閱片段。謝謝 –
運行你的代碼片段後,我得到'TypeError:__complex__應該返回一個複雜的對象'。也許你打算返回'self._value'而不是'self'?當我替換它時,會打印兩行:'[0. + 0.j0 + 0.j0 + 0.j]'和[[+ 0.j0 + 0.j0 + 0.j]'。我在Python 2.7.3上。 – dbkaplun