Python integer * float = NotImplemented

时间:2011-07-16 05:15:05

标签: python operator-keyword

当我发现这个有趣的事实时,我正在乱写一个矢量类。

>>> 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)

1 个答案:

答案 0 :(得分:11)

那是因为当你3 * 3.0执行(3.0).__rmul__(3)时,我意识到(3).__mul__(3.0)没有实现

Float的__mul____rmul__函数会将整数转换为浮点数,但int类不会发生这种情况。

否则3 * 3.5将是9而不是10.5

第二个问题:

为什么人们在列表推导(和生成器表达式)更好的时候坚持map

试试:

def __mul__(self, scalar):
    return Vector(scalar * j for j in self)

你应该对班上的其他所有功能都这样做。