課程
/后端開發(fā)
/Python
/Python開發(fā)簡單爬蟲
這條代碼是干什么用的,可以去掉嗎?
2016-03-20
源自:Python開發(fā)簡單爬蟲 7-2
正在回答
初次接觸Python的人會(huì)很不習(xí)慣Python沒有main主函數(shù)。這里簡單的介紹一下,在Python中使用main函數(shù)的方法#hello.pydef foo():????str="function"????print(str);if __name__=="__main__":????print("main")????foo()其中if __name__=="__main__":這個(gè)程序塊類似與Java和C語言的中main(主)函數(shù)在Cmd中運(yùn)行結(jié)果C:\work\python\divepy>python hello.pymainfunction在Python Shell中運(yùn)行結(jié)果>>> import hello>>> hello.foo()function>>> hello.__name__'hello'>>>可以發(fā)現(xiàn)這個(gè)內(nèi)置屬性__name__自動(dòng)的發(fā)生了變化。這是由于當(dāng)你以單個(gè)文件運(yùn)行時(shí),__name__便是__main__當(dāng)你以模塊導(dǎo)入使用時(shí),這個(gè)屬性便是這個(gè)模塊的名字。————kaitianmao
mirrornighthehe 提問者
舉報(bào)
本教程帶您解開python爬蟲這門神奇技術(shù)的面紗
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網(wǎng)安備11010802030151號
購課補(bǔ)貼聯(lián)系客服咨詢優(yōu)惠詳情
慕課網(wǎng)APP您的移動(dòng)學(xué)習(xí)伙伴
掃描二維碼關(guān)注慕課網(wǎng)微信公眾號
2016-03-20
初次接觸Python的人會(huì)很不習(xí)慣Python沒有main主函數(shù)。
這里簡單的介紹一下,在Python中使用main函數(shù)的方法
#hello.py
def foo():
????str="function"
????print(str);
if __name__=="__main__":
????print("main")
????foo()
其中if __name__=="__main__":這個(gè)程序塊類似與Java和C語言的中main(主)函數(shù)
在Cmd中運(yùn)行結(jié)果
C:\work\python\divepy>python hello.py
main
function
在Python Shell中運(yùn)行結(jié)果
>>> import hello
>>> hello.foo()
function
>>> hello.__name__
'hello'
>>>
可以發(fā)現(xiàn)這個(gè)內(nèi)置屬性__name__自動(dòng)的發(fā)生了變化。
這是由于當(dāng)你以單個(gè)文件運(yùn)行時(shí),__name__便是__main__
當(dāng)你以模塊導(dǎo)入使用時(shí),這個(gè)屬性便是這個(gè)模塊的名字。————kaitianmao