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