some basic questions...
marcus at deepfort.com
marcus at deepfort.com
Thu Sep 23 00:15:03 CEST 2004
>When a file containing python code is executed, the built in variable _name_
>is populated with the name of the module being executed. If the value of
>_name_ is _main_, then that file is the original file that was used to
>invoke the application from command line or an icon.
>This is usefull, as it allows code to know the difference between when it is
>invoked & when it is imported by another python program. It is also provides
>a convenient place to provide one-time startup code.
>Can someone explain this in some different wording, because I dn't know if
>my understanding of what is said in that paragraph is right or not?
*When you import a python module, the value in that module's __name__
attribute will be its own name.
When you "run" the same python module, the value in that module's
__name__ attribute will be "__main__"*
That means, simply, you can differentiate between the module that is
being explicitly run, say from a shell, and the module that is imported,
by looking at the particular module's __name__ attribute.
You can demonstrate this to yourself thus:
1. run a python file(module) in interactive mode and look at the value
you at host$ python -i test.py
2. in a new python shell, import the same python module and look at the
value of module.__name__
you at host$ python
Python 2.3.4 (May 29 2004, 19:23:07)
[GCC(ellipsis)] on HesnottheMessiahhesaverynaughtyboy
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
I hope that demonstrates it, and yes, it's probably a terrible example
(use a module which exists in your path for the second one :-) )
So say where you had:
if __name__ == '__main__':
x = Application(width, height)
if __name__ == '__main__': - means "only run the next bit of code if
this module is explicitly run, and ignore it if this module is imported."
I've probably explained it really, really badly.
Good to see another mere mortal on the list though :-)
>Can somebody explain what the, "self" is actually for??
The self points back to the instance you will create at runtime. The
best thing I can suggest for that is to get used to using it, as it will
make more and more sense to you as you go on. (Some would growl that's
debatable - not me though :-) )
More information about the Python-list