A number of other questions are now marked as duplicates of this question, and at least two of them ask what either the __spam__
methods are called, or what the convention is called, and none of the existing answers cover that, so:
There actually is no official name for either.
Many developers unofficially call them "dunder methods", for "Double UNDERscore".
Some people use the term "magic methods", but that's somewhat ambiguous between meaning dunder methods, special methods (see below), or something somewhere between the two.
There is an official term "special attributes", which overlaps closely but not completely with dunder methods. The Data Model chapter in the reference never quite explains what a special attribute is, but the basic idea is that it's at least one of the following:
- An attribute that's provided by the interpreter itself or its builtin code, like
__name__
on a function.
- An attribute that's part of a protocol implemented by the interpreter itself, like
__add__
for the +
operator, or __getitem__
for indexing and slicing.
- An attribute that the interpreter is allowed to look up specially, by ignoring the instance and going right to the class, like
__add__
again.
Most special attributes are methods, but not all (e.g., __name__
isn't). And most use the "dunder" convention, but not all (e.g., the next
method on iterators in Python 2.x).
And meanwhile, most dunder methods are special attributes, but not all—in particular, it's not that uncommon for stdlib or external libraries to want to define their own protocols that work the same way, like the pickle
protocol.