python中 __name__及__main()__的妙处02
python中 __name__及__main()__的妙處
#hello.pydef sayHello():
str="hello"
print(str);
if __name__ == "__main__":
print ('This is main of module "hello.py"')
sayHello()
python作為一種腳本語言,我們用python寫的各個(gè)module都可以包含以上那么一個(gè)累死c中的main函數(shù),只不過python中的這種__main__與c中有一些區(qū)別,主要體現(xiàn)在:
1、當(dāng)單獨(dú)執(zhí)行該module時(shí),比如單獨(dú)執(zhí)行以上hello.py: python hello.py,則輸出
????
This?is?main of module?"hello.py"hello
?
?
?
??? 可以理解為"if __name__=="__main__":" 這一句與c中的main()函數(shù)所表述的是一致的,即作為入口;
2、當(dāng)該module被其它module 引入使用時(shí),其中的"if __name__=="__main__":"所表示的Block不會(huì)被執(zhí)行,這是因?yàn)榇藭r(shí)module被其它module引用時(shí),其__name__的 值將發(fā)生變化,__name__的值將會(huì)是module的名字。比如在python shell中import hello后,查看hello.__name__:
>>>?import?hello>>>?hello.__name__
'hello'
>>>
3、因此,在python中,當(dāng)一個(gè)module作為整體被執(zhí)行時(shí),moduel.__name__的值將是"__main__";而當(dāng)一個(gè) module被其它module引用時(shí),module.__name__將是module自己的名字,當(dāng)然一個(gè)module被其它module引用時(shí),其 本身并不需要一個(gè)可執(zhí)行的入口main了。可以說python中的這種用法很靈活啊。
?
轉(zhuǎn)自:http://www.cnblogs.com/liqilei/archive/2010/08/11/1797715.html
轉(zhuǎn)載于:https://www.cnblogs.com/handsome1013/p/9269200.html
總結(jié)
以上是生活随笔為你收集整理的python中 __name__及__main()__的妙处02的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS 开发 需要的版本管理工具,UI图
- 下一篇: django2.0集成xadmin0.6