gpt4 book ai didi

python - 在python中重载任意运算符

转载 作者:行者123 更新时间:2023-12-04 09:31:17 24 4
gpt4 key购买 nike

是否可以在 Python 中重载任意运算符?或者是一种仅限于具有相关魔术方法的运算符列表,如下所列:https://www.python-course.eu/python3_magic_methods.php ?
我问是因为我注意到 Numpy 使用 @ 运算符来执行矩阵乘法,例如C=A@B 其中 A,B 是 Numpy 数组,我想知道他们是如何做到的。
编辑:@ 运算符不在我链接的列表中。
有人可以指出我完成此操作的 Numpy 源代码吗?

最佳答案

在 Python 中,您不能创建新的运算符,不。通过定义这些“魔法”函数,您可以影响使用标准运算符操作您自己定义的对象时会发生什么。
但是,您链接到的列表并不完整。在 Python 3.5 中,他们为 @ 添加了特殊方法。运算符(operator)。 Here's the rather terse listing in the Python operator module docshere 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
所以,不,你不能重载任何随机字符,但你可以重载 @运算符(operator)。

关于python - 在python中重载任意运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62831383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com