尝试使用__div__重新定义除法运算符时出错

时间:2016-09-09 15:15:11

标签: python python-2.7 numpy

为什么numpy会为以下代码抛出异常? foo/3工作正常。

import numpy as np

class item(object):
    def __init__(self, val = 0.0):
        self._val = val
    @property
    def value(self):
        return self._val
    def __add__(self, other):
        return item(self.value + other.value)
    def __sub__(self, other):
        return item(self.value - other.value)
    def __mul__(self, other):
        if isinstance(other, item):
            return self.value * other.value
        if isinstance(other, (int, float, long)):
            return item(other*self.value)
        raise TypeError("unsupported operand")
    def __div__(self, other):
        if isinstance(other, (int, float, long)):
            return item(self.value/other)
        raise TypeError("unsupported operand")
    def __cmp__(self, other):
        if self.value < other.value:
            return -1
        if self.value == other.value:
            return 0
        return 1
    def __str__(self):
        return "item <%f>" % self.value


data = [ item(x) for x in np.random.random(size = 1000) ]

foo = item(3.1)

foo/3

np.mean(data)

错误消息:

     45 foo/3
     46 
---> 47 np.mean(data)
     48 

/usr/lib/python2.7/dist-packages/numpy/core/fromnumeric.pyc in mean(a, axis, dtype, out, keepdims)    2714     2715     return
_methods._mean(a, axis=axis, dtype=dtype,
-> 2716                             out=out, keepdims=keepdims)    2717     2718 def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):

/usr/lib/python2.7/dist-packages/numpy/core/_methods.pyc in _mean(a, axis, dtype, out, keepdims)
     67         ret = ret.dtype.type(ret / rcount)
     68     else:
---> 69         ret = ret / rcount
     70 
     71     return ret

TypeError: unsupported operand type(s) for /: 'item' and 'int'

1 个答案:

答案 0 :(得分:3)

我需要定义__truediv__。文档说:

  

对象。__div__(自我,其他)

     

对象。__truediv__(自我,其他)

     

除法运算符(/)由这些方法实现。该   __truediv__()生效时使用__future__.division方法,否则使用__div__()。如果这两种方法中只有一种是   定义后,该对象将不支持替代中的除法   上下文;将引发TypeError。

请参阅https://docs.python.org/2.7/reference/datamodel.html?highlight=len#object.truediv