some basic questions...

Gerrit gerrit at nl.linux.org
Mon Sep 20 13:46:24 EDT 2004


Player wrote:
> [book quote]
> 
> 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?

A .py file can be executed in several ways. When you use 'import foo',
the value of 'foo.__name__' is "foo". When you start foo.py directly,
the value of __name__ is '__main__':

Suppose the content of foo.py is:

print __name__

Now let's run it from the commandline:

$ python foo.py
__main__

What happens when we import it as a module?

>>> import foo
foo

The same code gets executed, but with a different result.
So, the special variable '__main__' gives us a way to tell the
difference: are we being executed "directly by the user", or are we
being used as a library? In many occasions, we want to act differently.
What is seen often is this:

if __name__ == '__main__':
    main()

This executed the main() function if and only if the .py file is being
run directly from the commandline or from Windows. If we import the
file, we may not want to run the program at all: the if-block prevents
it.

See also:
http://www.python.org/doc/faq/programming.html#how-do-i-find-the-current-module-name
:

A module can find out its own module name by looking at the predefined
global variable __name__. If this has the value '__main__', the program
is running as a script. Many modules that are usually used by importing
them also provide a command-line interface or a self-test, and only
execute this code after checking __name__:

def main():
    print 'Running test...'
    ...

if __name__ == '__main__':
    main()

> Can somebody explain what the, "self" is actually for??

Well, that's a long story, it's all about Object Oriented Programming.
In short, 'self' is, well, self:

>>> class Foo(object):
...  def method(self):
...   return self
...
>>> f = Foo()
>>> f.method() == f
True


See also:
http://www.python.org/doc/faq/programming.html#what-is-self :

Self is merely a conventional name for the first argument of a method. A
method defined as meth(self, a, b, c) should be called as x.meth(a, b,
c) for some instance x of the class in which the definition occurs; the
called method will think it is called as meth(x, a, b, c).

hope this helps,
Gerrit Holl.

-- 
Weather in Twenthe, Netherlands 20/09 18:25:
	13.0°C   wind 8.9 m/s SSW (57 m above NAP)
-- 
Gerrit Holl - 2nd year student of Applied Physics, Twente University, NL.
Experiences with Asperger's Syndrome:
	EN http://topjaklont.student.utwente.nl/english/
	NL http://topjaklont.student.utwente.nl/



More information about the Python-list mailing list