类特殊方法行为__complex__

时间:2012-06-08 14:54:01

标签: python

我有一个定义__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

1 个答案:

答案 0 :(得分:3)

有两种选择:

  1. 定义__rmul__(或定义__mul__并翻转乘法操作数。)
  2. 在倍增之前将MyNumericClass实例投射到complex