「if __name__ == __main__:」的作用:指定主方法函數。在腳本執行時開啟main函數,但是在其他檔案import呼叫時不會執行。
一個python的檔案有兩種使用的方法,第一是直接作為腳本執行,第二是在其他檔案的python腳本中被import即呼叫(模組重用)執行。因此if name == 'main':的作用就是控制這兩種情況執行程式碼的過程,在if name == 'main':下的程式碼只有在第一種情況下(即檔案作為腳本直接執行)才會被執行,而import到其他腳本中是不會被執行的。
範例:
# file one.pydef func(): print("func() in one.py") print("top-level in one.py")if __name__ == "__main__": print("one.py is being run directly")else: print("one.py is being imported into another module")
# file two.pyimport one # start executing one.pyprint("top-level in two.py") one.func()if __name__ == "__main__": print("two.py is being run directly")else: print("two.py is being imported into another module")
當運行python one.py,輸出:
top-level in one.py one.py is being run directly
當運行python two.py,輸出:
top-level in one.py one.py is being imported into another module top-level in one.pyfunc() in one.py two.py is being run directly
以上是「if __name__ == __main__:」有什麼作用的詳細內容。更多資訊請關注PHP中文網其他相關文章!