允许 python 个对象与数学运算符交互

Allow python objects to interact with mathematical operators

我问这个是因为我记得 numpy 是用数组来做的。我应该添加两个包含单项式的对象。

或者,是否可以创建自定义数学运算符? (比如numpy点积的@)

这是很有可能的。 类 可以包含 "magic methods" 可以允许对象与 + 和其他运算符交互。具体来说,文档的 this 部分是相关的,尽管快速阅读整个文档会很有帮助。

link中最相关的方法:

object.__add__(self, other)
object.__sub__(self, other)
object.__mul__(self, other)
object.__matmul__(self, other)
object.__truediv__(self, other)
object.__floordiv__(self, other)
object.__mod__(self, other)
object.__divmod__(self, other)
例如,

@ 可以通过实现 __matmul__ 方法来使用:

class T:
    def __matmul__(self, other_t):
        pass

print(T() @ T())

您不能创建 "custom" 语言中尚不存在的运算符,但您可以使用现有运算符的任何挂钩。