Python 尝试用_div重新定义除法运算符时出错__
为什么numpy会对以下代码引发异常<代码>foo/3工作正常Python 尝试用_div重新定义除法运算符时出错__,python,python-2.7,numpy,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 +
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)
我需要定义
\uuuu truediv\uuuu
。文件说:
对象。\uuuu div\uuuuu
(自身、其他)
对象。\uuuu truediv\uuuu
(自身,其他)
除法运算符(/)由这些方法实现。这个
\uuuuu truediv\uuuu()方法在\uuuu future\uuuu.division
生效时使用,否则使用\uuuuu div()。如果这两种方法中只有一种是
定义后,该对象将不支持在替换中进行分割
上下文将改为引发TypeError
请参见在python2.7上对我有效。在python3上,它给了我您提到的错误,这是因为您必须使用\uuuu floordiv\uuu
和\uuu truediv\uuu
而不是\uu div\uuuu
。例如,见。您确定使用的是python 2.7吗?计算2/3
时得到的输出是什么?表达式(第(2)/3项)。value
返回0。我猜numpy使用的是\uuuuuuuuuuuuuuuuu.division
。
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'