开发者

Python: Difference between add and __add__

开发者 https://www.devze.com 2023-02-26 05:31 出处:网络
I开发者_高级运维n Python, what is the difference between add and __add__ methods?A method called add is just that - a method with that name. It has no special meaning whatsoever to the language or the

I开发者_高级运维n Python, what is the difference between add and __add__ methods?


A method called add is just that - a method with that name. 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. 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.


If you just went through this doc https://docs.python.org/3/library/operator.html and was curious about the differences between e.g.

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

Check the source code 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


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.

See this post for an elaborate argument

0

精彩评论

暂无评论...
验证码 换一张
取 消