在 python 中重载任意运算符

overloading arbitrary operator in python

是否可以在 Python 中重载任意运算符?或者是否仅限于具有此处列出的关联魔法方法的运算符列表:https://www.python-course.eu/python3_magic_methods.php ?

我问是因为我注意到 Numpy 使用 @ 运算符来执行矩阵乘法,例如C=A@B 其中 A、B 是 Numpy 数组,我想知道他们是怎么做到的。

编辑:@ 运算符不在我链接到的列表中。

有人可以告诉我完成此操作的 Numpy 源代码吗?

在Python中,您不能创建新的运算符,不行。通过定义这些“神奇”函数,您可以影响使用标准运算符对您自己定义的对象进行操作时发生的情况。

但是,您链接到的列表并不完整。在 Python 3.5 中,他们为 @ 运算符添加了特殊方法。 Here's the rather terse listing in the Python operator module docs and here are the docs on operator overloading.

operator.matmul(a, b)

operator.__matmul__(a, b)

Return a @ b.

New in version 3.5.

我没有亲眼见过那个接线员,所以我做了更多的研究。它专门用于 matrix multiplication。但是,我能够将它用于其他目的,尽管从风格上我反对这样做:

In [1]: class RichGuyEmailAddress(str): 
   ...:     def __matmul__(self, domain_name): 
   ...:         return f'{self}@{domain_name}' 
   ...:                                                                                                                                                                                       

In [2]: my_email = RichGuyEmailAddress('billg') @ 'microsoft.com'                                                                                                                              

In [3]: print(my_email)                                                                                                                                                                       
billg@microsoft.com

所以,不,你不能重载任何随机字符,但你可以重载 @ 运算符。