I am relatively new to the Python language and encountered this in doing the following:
help(list)
Here is what I encountered:
__add__(...)
| x.__add__(y) <==> x+y
|
| __contains__(...)
| x.__contains__(y) <==> y in x
|
| __delitem__(...)
| x.__delitem__(y) <==> del x[y]
Regarding these, what are the underscores for? Because they aren't used (to my knowledge) when you use a method normally, I'm struggling to understand why they'd take the time to write them out with underscores in the documentation.
Here is Guido van Rossum, the creator of Python, explaining the use of double underscores:
...
Also see the Python documentation on special method names which reads in part:
They are special methods (not the "dunder" (double underscore) makes them special, but most often they have a special meaning). They are often called when using operators. You can overwrite the behaviour in your classes.
E.g if you have a class
C
, by definingyou can define what should happen if you add two instances from the class:
In this case, double underscores are used as a convention to denote special methods - methods that are implemented to support syntactic sugar purposes and other special interfaces.
http://docs.python.org/reference/datamodel.html#specialnames
Wrapping a method name in underscores is just a way to separate namespaces. If a method begins and ends with underscores, it's simply a convention to indicate that the method isn't meant to be used by external code.
The blurb from
help(list)
you posted simply means that when you use Python's syntax to saye in lst
, you're actually invokinglst.__contains__(e)
.See the Python style guide for a comprehensive explanation.
In practice:
To some extent, these underscores are nothing special; they're just part of the method name.
However, they are used to indicate "magical" methods, such as constructors and overloaded operators. You should not use them in your own method names. From PEP 8:
You will rarely have to call any of these directly. For example:
MyClass(...)
will callMyClass.__init__(...)
,a + b
will calla.__plus__(b)
,str(a)
will calla.__str__()
.