【问题标题】:Python integer * float = NotImplementedPython 整数 * 浮点 = 未实现
【发布时间】: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

标签: python operator-keyword


【解决方案1】:

那是因为当您执行 3 * 3.0 时,解释器在意识到 (3).__mul__(3.0) 未实现后调用 (3.0).__rmul__(3)

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

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

第二个问题:

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

试试看:

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

你应该对类中的所有其他函数都这样做。

【讨论】:

  • 只是缺乏思考。我最近发现了函数式编程,并且只是想映射/减少所有内容。不过,完全和你一起改变。
  • @Ceasar 没关系,但请记住,推导式更具可读性(99.99% 的时间),并且是地图/过滤器的最终替代品。 Reduce 永远不会被使用(在 Python 中)!
猜你喜欢
  • 2017-07-26
  • 2020-07-26
  • 1970-01-01
  • 2018-06-16
  • 2020-11-30
  • 1970-01-01
  • 2021-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多