【问题标题】:Python: Operating on separate types [duplicate]Python:对不同类型进行操作[重复]
【发布时间】:2015-12-06 02:15:25
【问题描述】:

我正在作为 Python 中矢量类的空闲时间项目工作,以测试自己。有足够数学背景的人都知道,一个向量可以乘一个标量; 2 * (1, 2) = (2 * 1, 2 * 2) = (2, 4)。

这在 C# 中很简单。 public static operator *(int scalar, Vector vector) 并继续定义它。但是当我尝试在 Python 中做最明显的路线时,它会向我抛出一个 TypeError:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'int' and 'Vector'

当我将操作数的顺序反转为Vector * scalar 时,也会出现这种情况。

现在,我知道,在 Python 中,字符串等可迭代对象可以相乘:例如"abc" * 2 产生 "abcabc"。我的问题是:这只是语言的固有特性,还是有办法编写多类型运算符?

代码:

class Vector:
        def __init__(self, *contents):
            self.__c = contents

        def __iter__(self):
            return iter(self.__c)

        def __add__(u, v):
            exceptIfUnequal(u, v, "add") # <-- This is just a method that will raise an error if the vectors are unequal, it's unimportant to us
            return Vector(*[a + b for a, b in zip(u, v)])

        def __sub__(u, v):
            exceptIfUnequal(u, v, "subtract")
            return a + (-b)

        def __neg__(u):
            return Vector(-a for a in u)

        def __mult__(k, u):
            return Vector(*[k * a for a in u])
#I'm aware that logistically, k and u will need to be reversed if I want to reverse the order

        def __len__(u):
            return len(u.__c)

        def __str__(self):
            s = "<" + "{}, " * (len(self.__c) - 1) + "{}>"
            return s.format(*self.__c)

那么我能做些什么来完成这项工作吗?还是根本不可能?

编辑:你不知​​道吗,这是一个愚蠢的错误。正确的 Python 乘法是 __mul__,而不是 - 正如我所写的 - __mult__ - 带有 t。但更具体地说,我想要的项目是 __rmul__,它允许我以标量 * 向量的顺序相乘。

【问题讨论】:

  • 我相信是_mul_,而不是_mult_
  • 您只是拼错了方法名称。您还想在此处实现__rmult__,用于int * Vector 操作。您还想坚持使用self 作为第一个参数。
  • 非常感谢,Martijn!现在我觉得有点傻。但我很高兴你提出 rmult,因为这正是我所需要的!非常感谢!

标签: python exception operator-overloading


【解决方案1】:

你正在做的应该工作,你只是有错误的方法名称。应该是__mul__

虽然我认为如果您想同时支持int * VectorVector * Vector,它会更加细微。您将需要为此方法添加更多内容。

阅读此处了解更多信息https://docs.python.org/2/reference/datamodel.html#emulating-numeric-types

【讨论】:

    猜你喜欢
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    相关资源
    最近更新 更多