简体   繁体   English

Python:add 和 __add__ 之间的区别

[英]Python: Difference between add and __add__

在 Python 中, add<\/code>和__add__<\/code>方法有什么区别?

"

A method called add is just that - a method with that name. 一个名为add的方法就是 - 具有该名称的方法。 It has no special meaning whatsoever to the language or the interpreter. 它对语言或翻译没有任何特殊意义。 The only other thing that could be said about it is that sets have a method with the same name. 关于它的唯一可以说的是集合具有相同名称的方法。 That's it, nothing special about it. 就是这样,没什么特别的。

The method __add__ is called internally by the + operator, so it gets special attention in the language spec and by the interpreter and you override it to define addition for object of a class. 方法__add__+运算符在内部调用,因此它在语言规范和解释器中得到特别关注,并覆盖它以定义类对象的加法。 You don't call it directly (you can - they're still normal methods, they only get called implicitly in some circumstances and have some extra restrictions - but there's rarely if ever a reason - let alone a good reason). 你不直接调用它(你可以-他们仍然是正常的方法,他们只得到在某些情况下隐式调用,并有一些额外的限制-不过要是真有很少有原因的-更不用说一个很好的理由)。 See the docs on "special" methods for details and a complete list of other "special" methods. 有关详细信息,请参阅有关“特殊”方法文档,以及其他“特殊”方法的完整列表。

To add to the earlier posts, __*__ are often discouraged as names for identifiers in own-classes unless one is doing some hacking on core-python functionality, like modifying / over-loading standard operators, etc. And also, often such names are linked with magical behavior, so it might be wise to avoid using them in own-namespaces unless the magical nature of a method is implied. 要添加到早期的帖子, __*__通常不鼓励作为自己类中标识符的名称,除非有人对core-python功能进行了一些攻击,比如修改/重载标准运算符等等。而且,通常这样的名称与魔法行为相关联,因此避免在自己的命名空间中使用它们可能是明智的,除非暗示了方法的神奇本质。

See this post for an elaborate argument 请参阅此帖子以获得详尽的论据

If you just went through this doc https://docs.python.org/3/library/operator.html and was curious about the differences between eg如果您刚刚浏览了此文档https://docs.python.org/3/library/operator.html并且对例如之间的差异感到好奇

operator.add(a, b)
operator.__add__(a, b)

Check the source code https://github.com/python/cpython/blob/3.10/Lib/operator.py :查看源代码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

So所以

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM