时间:2023-02-20 02:12:02 | 来源:建站知识
时间:2023-02-20 02:12:02 来源:建站知识
python “__name__”到底是什么东西!:if __name__ == "__main__":,那么有没有人知道这到底是干嘛的。今天就分享一下这个到底是干嘛的。code0516。然后在这个文件夹下创建一个名叫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下,创建另外一个叫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。关键词: