【发布时间】:2011-07-16 05:15:05
【问题描述】:
所以当我发现这个有趣的事实时,我正在写一个向量类。
>>> e = int(3)
>>> e.__mul__(3.0)
NotImplemented
谁能解释为什么会这样,以及如何修复我的矢量类?
class Vector(tuple):
'''A vector representation.'''
def __init__(self, iterable):
super(Vector, self).__init__(iterable)
def __add__(self, other):
return Vector(map(operator.add, self, other))
def __sub__(self, other):
return Vector(map(operator.sub, self, other))
def __mul__(self, scalar):
return Vector(map(scalar.__mul__, self))
def __rmul__(self, scalar):
return Vector(map(scalar.__mul__, self))
def __div__(self, scalar):
return Vector(map(scalar.__rdiv__, self))
编辑:更清楚一点:
>>> a = Vector([10, 20])
>>> a
(10, 20)
>>> b = a / 2.0
>>> b
(5.0, 10.0)
>>> 2 * b
(NotImplemented, NotImplemented)
【问题讨论】:
-
您需要在
Vector课程中解决什么问题? -
Vector类和两行例子有什么关系???
-
那么,你的向量类有什么问题?
-
没有完整的答案,但是,我认为将整数和浮点数相乘会触发浮点数的 mul 方法,因为在此类操作中,python 总是将变量推向更复杂的方向.
-
也可以考虑使用
numpy.array。