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 回答