这是什么,为什么应该包括一个 if 声明?

if __name__ == "__main__":
    print("Hello, World!")

如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。


当前回答

简单地说,这是运行文件的输入点,就像C编程语言的主要功能一样。

其他回答

当一个 Python 文件运行时,它创建了许多特殊变量,如 __name__. 变量 __name__ 保留了文件的名称。

if __name__ == "__main__":
       # Do something

这意味着,如果执行的文件的名称运行为源文件而不是模块,那么它将运行代码在其中。 这可以通过一个简单的例子证明。 创建两个 Python 文件, foo.py 和 second.py. 然后在 foo.py 中输入此:

if __name__ == "__main__":
       print("file is not imported")
else:
       print("file is imported")

在第二.py 中,输入此:

import foo

if foo.__name__ == "__main__":
       print("file is not imported")
else:
       print("file is imported")

除此之外,如果你要做这个打印(__name__),那么它会打印 __main__。

因为文件是作为主要来源运行,如果你打印(foo.__name__)它将打印 foo 因为默认值的 __name__ 变量是文件的名称,默认情况下我意味着你也可以更改它。

__name__ = "Hello, World!"
print(__name__)

然后,产量将是:

Hello, World!

您可以通过这个简单的例子查看特殊变量 __name__:

创建 file1.py

if __name__ == "__main__":
    print("file1 is being run directly")
else:
    print("file1 is being imported")

创建 *file2.py

import file1 as f1

print("__name__ from file1: {}".format(f1.__name__))
print("__name__ from file2: {}".format(__name__))

if __name__ == "__main__":
    print("file2 is being run directly")
else:
    print("file2 is being imported")

执行 file2.py

出口:

file1 is being imported
__name__ from file1: file1
__name__ from file2: __main__
file2 is being run directly

在 Python 中,每个模块都有一个称为 __name__ 的属性. __name__ 的值是 __main__ 当模块直接运行时,如 python my_module.py. 否则(如您说 import my_module) __name__ 的值是模块的名称。

一个小例子要简要解释。

脚本测试.py

apple = 42

def hello_world():
    print("I am inside hello_world")

if __name__ == "__main__":
    print("Value of __name__ is: ", __name__)
    print("Going to call hello_world")
    hello_world()

我们可以直接这样做。

python test.py

出口

Value of __name__ is: __main__
Going to call hello_world
I am inside hello_world

现在假设我们从另一个脚本中称之为上面的脚本:

编辑 external_calling.py

import test

print(test.apple)
test.hello_world()

print(test.__name__)

当你执行这一点时,

python external_calling.py

出口

42
I am inside hello_world
test

因此,上述是自我解释的,当你从另一个脚本打电话测试时,如果在 test.py 中的 loop __name__ 不会执行。

考虑一下:

if __name__ == "__main__":
    main()

它检查Python脚本的 __name__属性是否是“__main__”。换句话说,如果程序本身执行,属性将是 __main__,因此程序将执行(在这种情况下,主()函数)。

但是,如果您的 Python 脚本是由一个模块使用的,任何代码外的,如果声明将执行,所以如果 __name__ ==“__main__”是用来检查程序是否作为一个模块使用,因此决定是否运行代码。

如果我们有两本书,

#script1.py
print "Script 1's name: {}".format(__name__)

#script2.py
import script1
print "Script 2's name: {}".format(__name__)

此分類上一篇: Executing script1

Script 1's name: __main__

执行脚本2的结果是:

Script1's name is script1
Script 2's name: __main__

正如你可以看到的那样, __name__ 告诉我们哪个代码是“主要”模块,这是很好的,因为你只能写代码,并且不需要担心结构问题,如在 C/C++ 中,如果一个文件不执行一个“主要”函数,那么它不能作为一个可执行的编写,如果是这样,它不能用作图书馆。

箭头是进口链接. 对于三个模块,每个试图包含以前的模块代码,有六个文件(九个,计算实施文件)和五个链接. 这使得很难将其他代码纳入一个C项目,除非它是专门编写为图书馆。

此分類上一篇