【发布时间】:2020-05-17 17:15:56
【问题描述】:
我问它是因为我记得 numpy 是用数组做的。我应该添加两个包含单项式的对象。
另外,是否可以创建自定义数学运算符? (就像numpy点积的@)
【问题讨论】:
标签: python python-3.x operators custom-operator
我问它是因为我记得 numpy 是用数组做的。我应该添加两个包含单项式的对象。
另外,是否可以创建自定义数学运算符? (就像numpy点积的@)
【问题讨论】:
标签: python python-3.x operators custom-operator
这是很有可能的。类可以包含允许对象与+ 和其他运算符交互的“魔术方法”。具体来说,文档的this 部分是相关的,尽管快速阅读整个文档会很有帮助。
该链接中最相关的方法:
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())
您不能创建该语言中尚不存在的“自定义”运算符,但您可以利用现有运算符中的任何挂钩。
【讨论】: