相信很多初學(xué)python的人看代碼的時(shí)候都會(huì)先找一下main()方法,從main往下看。但事實(shí)上python中是沒(méi)有你理解中的“main()”方法的。if__name__=="__main__":可以看成是python程序的入口,就像java中的main()方法,但不完全正確。
事實(shí)上python程序是從上而下逐行運(yùn)行的,在.py文件中,除了def后定義函數(shù)外的代碼都會(huì)被認(rèn)為是“main”方法中的內(nèi)容從上而下執(zhí)行。如果只是寫個(gè)偉大的"helloworld",不想寫函數(shù)的話,僅僅是print('helloworld')就可以,這就是一個(gè)“程序”,不需要所謂的“main”方法入口。當(dāng)然如果是測(cè)試函數(shù)功能就需要在.py文件中寫上if__name__=="__main__",再調(diào)用函數(shù)。比如下面的hello.py文件:
print("first")
defsayHello():
str="hello"
print(str);
print(__name__+'fromhello.sayhello()')
if__name__=="__main__":
print('Thisismainofmodule"hello.py"')
sayHello()
print(__name__+'fromhello.main')
運(yùn)行結(jié)果:
first
Thisismainofmodule"hello.py"
hello
__main__fromhello.sayhello()
__main__fromhello.main
懂我意思吧?先執(zhí)行的第一行print再執(zhí)行“入口”中的東西。
話說(shuō)回來(lái),if__name__=="__main__"這句話是個(gè)什么意思呢?
__name__其實(shí)是一個(gè)內(nèi)置屬性,指示當(dāng)前py文件調(diào)用方式的方法。當(dāng)上述例子運(yùn)行的時(shí)候,整個(gè)程序中不管是哪個(gè)位置的__name__屬性,值都是__main__,當(dāng)這個(gè)hello.py文件作為模塊被導(dǎo)入到另一個(gè).py文件中(即import)比如說(shuō)world.py,并且你運(yùn)行的是world.py,此時(shí)hello.py中的__name__屬性就會(huì)變成hello,所謂的入口因?yàn)閕f判斷失敗就不執(zhí)行了。
所以if語(yǔ)句的判斷成功虛擬了一個(gè)main()方法。
說(shuō)到了phthon是逐行執(zhí)行的,所以當(dāng)它讀到importhello的時(shí)候,也會(huì)執(zhí)行hello.py,比如運(yùn)行如下world.py文件:
importhello#上一個(gè)例子的hello.py
if__name__=="__main__":
print('Thisismainofmodule"world.py"')
hello.sayHello()
print(__name__)
執(zhí)行結(jié)果:
first
Thisismainofmodule"world.py"
hello
hellofromhello.sayhello()
__main__
可以看到hello.py中的第一行print('first')直接被執(zhí)行了,并且hello.py中的__name__輸出的也是hello,world.py中的name輸出的是__main__。
總結(jié):要適應(yīng)python沒(méi)有main()方法的特點(diǎn)。所謂的入口其實(shí)也就是個(gè)if條件語(yǔ)句,判斷成功就執(zhí)行一些代碼,失敗就跳過(guò)。沒(méi)有java等其他語(yǔ)言中那樣會(huì)有特定的內(nèi)置函數(shù)去識(shí)別main()方法入口,在main()方法中從上而下執(zhí)行。
以上內(nèi)容為大家介紹了python培訓(xùn)之沒(méi)有main函數(shù)嗎,希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。