[Tutor] Beginner Q: What does the double underscore mean __ ?

Dave Angel d at davea.name
Sun Sep 9 14:09:21 CEST 2012


On 09/09/2012 07:27 AM, Aaron Pilgrim wrote:
> Hi,
> I was trying to teach myself some python from a book and I have seen
> double underscores used.
> What does the __ mean and how do I know when to use it?
>
> for example:
>
> __name__==’__main__’
>
> (source)
> Pilgrim, Mark (2009-10-23). Dive Into Python 3 (Books for
> Professionals by Professionals) (Kindle Locations 480-481). Apress.
> Kindle Edition.
> _______________________________________________
>

Two places I know of where both leading and trailing underscores are
used in Python.  One is for special attributes like __name__ and __doc__
and the other is for special methods like __len__ and __str__

__name__ and __file__ are attributes of a module, which let you find out
things about what source file was imported to get that modjule. The name
"__main__" is used to flag the SCRIPT that you started;  nobody imports
that file, that's how you started this program running.

__doc__ is filled in by the compiler when it detects what's called a
docstring:  a literal string immediately following a def statement, a
class statement. The module docstring would have to be the first
executable line in the module, following the shebang and the encoding line.

The special methods are defined in a class to give it special behavior. 
For example, if a class acts like a collection, it'd be convenient to
define what the len() function does, so that it shows how many elements
are in the instance.  So, under the covers, the built-in len() function
calls the objects __len__() method.  A second example you use many times
without noticing is that when you call str() on an object, it looks for
a __str__() method.  If found, that's how the object is displayed.  If
not, you get the generic <__main__.X instance at 0x267da70> format
(differs by Python version).  Incidentally when you print an arbitrary
object, print calls str(), which may call __str__().

There are very few times you actually use such attributes or call such
methods;  __name__ is the only common one.  For example, you should use
str(), not __str__().  And you should use  a[4], not __getitem__

See http://docs.python.org/reference/datamodel.html, and search on that
page for "special methods"




-- 

DaveA



More information about the Tutor mailing list