if __name__ == "__main__"
也就是說執行當前檔案,不呼叫模塊的時候__name__=__main__
呼叫模塊的時候,測驗如下:
1、新建 test01.py 檔案測驗代碼如下
print("這條訊息來自test01")
def func():
print('hello, world!***')
print("這條訊息來自func")
if __name__ == "__main__":
func()
運行結果如下:
# 這條訊息來自test01 # hello, world!*** # 這條訊息來自func
2、新建 testo2.py 檔案測驗代碼如下
import test01
print(__name__)
test01.func() print('\n') print('這條訊息來自testo2') print('bye, world!') print(__name__)
運行結果如下:
# 這條訊息來自test01 --------------import test01 的時候輸出 # __main__ --------------輸出當前執行檔案的__name__ # hello, world!*** --------------下面這兩句呼叫函式test01.func()時輸出
# 這條訊息來自func #
# 這條訊息來自testo2 -------------繼續執行當前檔案的代碼塊
# bye, world!
# __main__
也就是說:
在 test2.py 檔案中匯入了 test1.py 模塊使用的是陳述句 import test1
那么在執行 test2.py 檔案的程序中,當執行到陳述句 import test1時,程式會跳轉去執行 test1.py 檔案
比如 print("這條訊息來自test01"),可能順便編譯了test01的函式,
因為沒有呼叫所以沒有執行,呼叫以后執行函式內部程式
關于模塊的理解大概就這樣,至于為什么要在檔案開頭寫這個if __name__ == "__main__",類似于java的主程式入口?大概接觸的專案太小,我是還沒有發現其妙用之處,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/548780.html
標籤:其他
