对于大多数编译型编程语言来说, 如C、C++、Java等,都会有一个main函数来作为函数的入口。而python则有所不同,它基本属于脚本语言,即从脚本的第一行开始逐行解释运行,没有统一的入口。而"if __name__=="__main__":" 这一句可以理解为主程序入口;
python是使用缩进对齐的方式执行的,对于没有缩进的代码,会在载入时自动执行。另外代码除了直接执行外,还可以作为模块调用。为了区分执行和调用,python引入了内置属性:__name__。
1. 当代码被执行时,__name__的值为 ‘__main__’
2. 当代码被调用时,如果在模块中,__name__就表示模块名;如果在类中,__name__就表示类名。
举个栗子:
在test_1.py中写入如下代码:
```
print "I'm the first..."
def test():
print "I'm the second..."
print __name__
if __name__ == "__main__":
test()
print "I'm the third..."
else:
print "I'm the last..."
```
直接执行test_1.py,会有如下结果:
```
C:\Python27\python.exe D:/userdata/f7yang/workspace/Python_test/test_libraries/test_study_10/test_1.py
I'm the first...
__main__
I'm the second...
I'm the third...
```
可以看出,此时__name__的值为‘__main__’ ,
而作为调用来执行时:
`from test_1 import test`
会有如下结果:
```
C:\Python27\python.exe D:/userdata/f7yang/workspace/Python_test/test_libraries/test_study_10/test_2.py
I'm the first...
test_1
I'm the last...
```
此时__name__的值为test_1,即模块的名字 。
其实简而言之,自动执行类似自己称呼自己,调用则类似别人称呼自己,如是而已。