時間:2023-02-20 02:12:02 | 來源:建站知識
時間:2023-02-20 02:12:02 來源:建站知識
python “__name__”到底是什么東西?。?h2 data-first-child>背景大家經常在 python 的腳本文件中,會遇到這樣的代碼:if __name__ == "__main__":
,那么有沒有人知道這到底是干嘛的。今天就分享一下這個到底是干嘛的。code0516
。然后在這個文件夾下創(chuàng)建一個名叫one.py
文件,并且寫入下面的代碼:# file one.pydef func(): # Line 1.1 print("func() in ONE.py")print("top-level in ONE.py") # line 1.2if __name__ == "__main__": print("ONE.py is being run directly") # line 1.3else: print(f"ONE.py __name__ is {__name__}") # line 1.4 print("ONE.py is being imported into another module") # line 1.5
然后運行:python one.py
,運行結果如下:# line 1.2
、# line 1.3
部分都運行了,別的都沒運行。python one.py
命令運行one.py
文件,叫直接運行。(感覺說了就像是沒說一樣)。__name__
其實是 python 的內置的一個變量。__name__
就成了__main__
。code0516
下,創(chuàng)建另外一個叫two.py
文件。并且寫入下面的代碼:# file two.pyimport oneprint("top-level in TWO.py") # line 2.1one.func() # line 2.2if __name__ == "__main__": print("TWO.py is being run directly") # line 2.3else: print("TWO.py is being imported into another module") # line 2.4
然后運行:python two.py
,運行結果如下:# line 1.2
、 # line 1.4
、# line 1.5
、# line 2.1
、# line 1.1
、# line 2.2
、# line 2.3
部分都運行了,別的都沒運行。two.py
文件運行的結果逐行分析一下,但是我們這里有下面幾個要求要注意:import one
這就是代表 導入運行
(就是導入這個文件,反正不是直接運行了)。import one
這樣的形式的),__name__
就成了腳本本身的名字了
,這里的腳本名字為one
,因此這里的__name__
也就變成了one
。two.py
直接運行分析運行結果 | 結果來源于哪一行 | 為什么會運行這一行 (two.py) |
---|---|---|
top-level in ONE.py | # line 1.2 | import one |
ONE.py __name__ is one | # line 1.4 | import one |
ONE.py is being imported into another module | # line 1.5 | import one |
top-level in TWO.py | # line 2.1 | print("top-level in TWO.py") |
func() in ONE.py | # Line 1.1 | one.func() |
TWO.py is being run directly | # line 2.3 | print("TWO.py is being run directly") |
python one.py
命令運行one.py
文件,叫直接運行。(感覺說了就像是沒說一樣)。__name__
其實是 python 的內置的一個變量。__name__
就成了__main__
。import one
這樣的形式的),__name__
就成了腳本本身的名字了
,這里的腳本名字為one
,因此這里的__name__
也就變成了one
。關鍵詞: