Python中if __name__ == '__main__':作用
分類: Python/Ruby
#hello.pydef sayHello():
str="hello"
print(str);
if __name__ == "__main__":
print ('This is main of module "hello.py"')
sayHello()
python作為一種腳本語言,我們用python寫的各個module都可以包含以上那么一個累死c中的main函數(shù),只不過python中的這種__main__與c中有一些區(qū)別,主要體現(xiàn)在:
1、當單獨執(zhí)行該module時,比如單獨執(zhí)行以上hello.py: python hello.py,則輸出
This is main of module "hello.py"hello
可以理解為"if __name__=="__main__":" 這一句與c中的main()函數(shù)所表述的是一致的,即作為入口;
2、當該module被其它module 引入使用時,其中的"if __name__=="__main__":"所表示的Block不會被執(zhí)行,這是因為此時module被其它module引用時,其__name__的值將發(fā)生變化,__name__的值將會是module的名字。比如在python shell中import hello后,查看hello.__name__:
>>> import hello>>> hello.__name__
'hello'
>>>
3、因此,在python中,當一個module作為整體被執(zhí)行時,moduel.__name__的值將是"__main__";而當一個module被其它module引用時,module.__name__將是module自己的名字,當然一個module被其它module引用時,其本身并不需要一個可執(zhí)行的入口main了。可以說python中的這種用法很靈活啊。
總結
以上是生活随笔為你收集整理的Python中if __name__ == '__main__':作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gcc选项
- 下一篇: 玉米转座子插入型突变体”五折优惠