Please explain Python "__whatever__" construct.

Benjamin Kaplan benjamin.kaplan at case.edu
Mon Jun 16 19:00:33 EDT 2008


On Mon, Jun 16, 2008 at 5:56 PM, <bsagert at gmail.com> wrote:

> After a couple of weeks studying Python, I already have a few useful
> scripts, including one that downloads 1500 Yahoo stock quotes in 6
> seconds. However, many things are puzzling to me. I keep on seeing
> things like "__main__" in scripts.  A more obscure example would be
> "__add__" used in string concatenation. For example, I can use "Hello
> "+"world (or just "Hello" "world") to join those two words. But I can
> also use "Hello ".__add__("world"). When and why would I ever use
> "__main__" or the many other "__whatever__" constructs?
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Constructs like this are, for the most part, "magic" methods
when you write "a + b", Python actually calls a.__add__(b). This allows you
to write your own methods. You could, say, write a fraction class and use
the statement "fraction1 + fraction2".

You should not call the magic methods explicitly. They only exist so you
could use other functions for them. The functions that use magic methods
include all of the operators (including comparison), len(obj), str(obj),
repr(obj), obj[i], obj[i:j], del obj, in, print, and many others.

There are also a couple of module constants that use the same format.
__file__ is the file path of script you are in. (in a file located at
C:\test\myscript.py, __file__ is "C:\\test\\myscript.py").
The other constant is __name__. __name__ is the name of the current script.
Using the same file as before, __name__ == "myscript". The only time this is
different is that the script that is executed always has a name of
"__main__". The most common place to see this used is in

if __name__ == "__main__" :
   <do something>

This specifies that the code will only run if the script is run as an
executable, not if it is imported by another module.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080616/7b0c1e32/attachment-0001.html>


More information about the Python-list mailing list