double underscore attributes?

Xavier Morel xavier.morel at masklinn.net
Sat Dec 10 17:33:56 EST 2005


bobueland at yahoo.com wrote:
> Could someone explain the use of __add__ (and similar double underscore
> attributes) and what their use is.
> 
> Bob
> 
Methods with double leading and trailing underscores are basically 
"magic methods" with specific meanings for the Python interpreter.

You're not supposed to use them directly (in most cases) as they are 
wrapped by syntactic sugar or part of protocol's implementation.

__add__, for example, is the definition of the "+" operator, using 
"(5).__add__(8)" is exactly the same as using "5+8".

To get a list of most of these magic methods, check the Python 
documentation on the "operator" module.

These magic methods allow you to emulate numbers, sequences, iterators, 
or even callables (allowing you to use an object as a function). Be 
really careful with them though, one of the things that plagued (and 
still plague) C++ is the abuse of operators overloading and modification 
of their meaning.



More information about the Python-list mailing list