__name__:模塊名
python中的模塊名可以分成兩類,一類是xxx.py文件,那麼模塊名就是xxx,例如test.py,那麼模塊名是test,調用方法就是import test;另一類是__main__,當直接運行xxx.py文件是,缺省調用的模塊名是__main__;
直接上代碼:
test.py
!/usr/bin/python
def func():
print("test 1")
print("test 2")
def main():
func()
if __name__ == "__main__":
print("test 3")
main()
else:
print("test 4")
運行結果:
test 2
test 3
test 1
分析:python是從上到下的運行順序,所以先執行test 2,因爲是直接運行,模塊名即爲__main__,調用if分支,先後執行test 3 ,test 1;
test2.py
import test
print("test 5")
test.func()
if __name__ == "__main__":
print("test 6")
else:
print("test 7")
運行結果:
test 2
test 4
test 5
test 1
test 6
分析:import test時,開始執行test.py,首先輸出test2,此時因爲是import 調用,模塊名爲test, 這時,調用了else分支,輸出test 4;對於test 2 而言,是直接運行,因此模塊名仍爲main。