0

__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
4

1 に答える 1

3

いくつかのオプション:

  1. 定義__rmul__します (または__mul__、乗算オペランドを定義して反転します)。
  2. 乗算する前にMyNumericClassインスタンスをキャストします。complex
于 2012-06-08T15:00:10.090 に答える