允许python对象与数学运算符进行交互[重复] 。

问题描述 投票:1回答:1

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

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

python python-3.x operators custom-operator
1个回答
2
投票

这是非常可能的。类可以包含 "神奇的方法",它可以让对象与 + 和其他运营商。具体来说。这个 的部分是相关的,尽管快速阅读整个文档会很有帮助。

该链接中最相关的方法。

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

你不能创建语言中没有的 "自定义 "操作符 但你可以利用任何一个钩子进入现有的操作符。

© www.soinside.com 2019 - 2024. All rights reserved.