2012-06-08 63 views
0

我有一個類定義了__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 
+3

在沒有看到代碼的情況下猜測問題可能會有點困難。你定義了__rmul __()嗎? –

+0

完成。請參閱片段。謝謝 –

+0

運行你的代碼片段後,我得到'TypeError:__complex__應該返回一個複雜的對象'。也許你打算返回'self._value'而不是'self'?當我替換它時,會打印兩行:'[0. + 0.j0 + 0.j0 + 0.j]'和[[+ 0.j0 + 0.j0 + 0.j]'。我在Python 2.7.3上。 – dbkaplun

回答

3

幾個選項:

  1. 定義__rmul__(或定義__mul__和翻轉乘法操作數)。
  2. 在乘以之前將MyNumericClass實例投射到complex
+1

小問題:python沒有強制轉換(你告訴語言內存中的內容實際上是另一種類型),你可以將它轉換成一個全新的對象(這可能會影響內存/性能)。 – Daenyth

+0

我很困惑你提出的解決方案我不是想要繁殖,我試圖給予一個真實的複雜的有價值的對象。例如,我想將我的對象的一個​​真實數組轉換爲複雜的,類似於numpy 'x = np.zeros(shape ).astype(複雜)' mylib.zeros創建一個我自定義數值對象的零的數組,類似於numpy。 –

+0

您能否提供導致上述TypError的最小示例? – dbkaplun