[英]Python: Difference between add and __add__
在 Python 中, add<\/code>和
__add__<\/code>方法有什么区别?
"
要添加到早期的帖子, __*__
通常不鼓励作为自己类中标识符的名称,除非有人对core-python功能进行了一些攻击,比如修改/重载标准运算符等等。而且,通常这样的名称与魔法行为相关联,因此避免在自己的命名空间中使用它们可能是明智的,除非暗示了方法的神奇本质。
请参阅此帖子以获得详尽的论据
如果您刚刚浏览了此文档https://docs.python.org/3/library/operator.html并且对例如之间的差异感到好奇
operator.add(a, b)
operator.__add__(a, b)
查看源代码https://github.com/python/cpython/blob/3.10/Lib/operator.py :
def add(a, b):
"Same as a + b."
return a + b
...
# All of these "__func__ = func" assignments have to happen after importing
# from _operator to make sure they're set to the right function
...
__add__ = add
所以
print(3+3) # call `operator.__add__` which is `operator.add`
import operator
print(operator.add(3, 3)) # call `operator.add` directory
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.