stackoverflow上有一个很好的解释。
When the Python interpreter reads a source file, it executes all of the code found in it.
Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special__name__variable to have a value"__main__". If this file is being imported from another module,__name__will be set to the module's name.
In the case of your script, let's assume that it's executing as the main function, e.g. you said something like
python threading_example.py
on the command line. After setting up the special variables, it will execute theimportstatement and load those modules. It will then evaluate thedefblock, creating a function object and creating a variable calledmyfunctionthat points to the function object. It will then read theifstatement and see that__name__does equal"__main__", so it will execute the block shown there.
One of the reasons for doing this is that sometimes you write a module (a.pyfile) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.
我主要翻译一下最后一部分:
你写的一个python程序,它可以直接运行,也可以被其他模块调用,我们使用这个判断,是要达到以下目的:
当别的py文件是被调用的时候,它自己不主动执行,它只做为其他程序的一部分。
还可以参考以下链接
http://ibiblio.org/g2swap/byteofpython/read/module-name.html
http://www.cnblogs.com/xuxm2007/archive/2010/08/04/1792463.html
是这样的,导入其他模块后,执行都会带着模块的名字。
$ python
>>> import using_name
之后程序做的事是判断if using_name.__name__=='__main__':
结果是比较if 'using_name'=='__main__':
不等于,执行using_name.py里的否定语句。
我猜测是这样的:
__name__=='__main__'
a.__name__=='a'
Python 模块(Module),是一个 Python 文件,以 .py 结尾
模块是对象,并且所有的模块都有一个内置属性 __name__。
一个模块的 __name__ 的值取决于您如何应用模块。
如果 import 一个模块,那么模块__name__ 的值通常为模块文件名,不带路径或者文件扩展名。
但是您也可以像一个标准的程序样直接运行模块,在这 种情况下, __name__ 的值将是一个特别缺省"__main__"。
当一个模块是被import的时候,__name__ 的值通常为模块文件名,此模块下没有if __name__ == "__main__"就算了,要是有就会给出否定结果,执行对应语句。
我猜模块被调用的时候,会立即把所有能执行的都执行了,试一下。
确实是这样。
被import立即执行的时候,__name__不是缺省的了,就是这样而已。