【发布时间】: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