【问题标题】:Error when trying to redefine the division operator with __div__尝试使用 __div__ 重新定义除法运算符时出错
【发布时间】:2016-09-09 15:15:11
【问题描述】:

为什么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'

【问题讨论】:

  • 在 python2.7 上为我工作。在 python3 上,它给了我你提到的错误,这是因为你必须使用 __floordiv____truediv__ 而不是 __div__。参见例如here。你确定你使用的是python 2.7吗?您评估2/3 得到的输出是什么?
  • 表达式 (item(2)/3).value 返回 0。
  • 我猜 numpy 正在使用__future__.division

标签: python python-2.7 numpy


【解决方案1】:

我需要定义__truediv__。文档说:

object.__div__(self, other)

object.__truediv__(self, other)

除法运算符 (/) 由这些方法实现。这 当__future__.division 生效时使用__truediv__() 方法,否则使用__div__()。如果这两种方法中只有一种是 已定义,该对象将不支持备用中的除法 语境;将改为引发 TypeError。

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

【讨论】:

    猜你喜欢
    • 2014-03-18
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多