<br><br><div class="gmail_quote">On Mon, Jun 16, 2008 at 5:56 PM,  <<a href="mailto:bsagert@gmail.com">bsagert@gmail.com</a>> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
After a couple of weeks studying Python, I already have a few useful<br>
scripts, including one that downloads 1500 Yahoo stock quotes in 6<br>
seconds. However, many things are puzzling to me. I keep on seeing<br>
things like "__main__" in scripts.  A more obscure example would be<br>
"__add__" used in string concatenation. For example, I can use "Hello<br>
"+"world (or just "Hello" "world") to join those two words. But I can<br>
also use "Hello ".__add__("world"). When and why would I ever use<br>
"__main__" or the many other "__whatever__" constructs?<br>
<font color="#888888">--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</font></blockquote></div><br>Constructs like this are, for the most part, "magic" methods<br>
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".<br>
<br>
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.<br>
<br>
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").<br>
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<br>
<br>
if __name__ == "__main__" :<br>
   <do something><br>
<br>This specifies that the code will only run if the script is run as an executable, not if it is imported by another module.<br>