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

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

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


当前回答

当您执行模块(源文件)时,条件是否检查模块是否直接被召唤或从另一个源文件被召唤。

如果直接呼吁执行,则模块名称将设置为“主”,然后在如果区块内的代码将执行。

其他回答

“如果”将允许您选择是否将Python文件作为模块或脚本

如果名称==‘主’ 然后 Python 文件是用作脚本 - 有逻辑在这个声明下,如果名称!=‘主’ 只有这个 Python 文件的功能/变量可以用在一些其他 Python 脚本

创建以下两个文件:

# a.py

import b
# b.py

print("__name__ equals " + __name__)

if __name__ == '__main__':
    print("if-statement was executed")

现在将每个文件单独运行。


使用 Python A.Py:

$ python a.py
__name__ equals b

当 a.py 运行时,它会导入 b 模块,这会导致 b 内部的所有代码运行。


运行Python b.py:

$ python b.py
__name__ equals __main__
if-statement was executed

当只执行 b.py 文件时,Python 在此文件中将 globals()['__name__'] 设置为 "__main__". 因此,如果声明评估为 True 这一次。

简单的答案是下方写的代码,如果名称 ==“主”:如果您将其输入到另一个文件,则不会执行。

例如,这是 test1.py 没有如果 __name__ ==“__main__”::

# "test1.py"

def hello()
    print("Hello")

hello()

而且 test2.py 只輸入 test1.py:

# "test2.py"

import test1 # Here


然后,当运行 test2.py 时,一个 Hello 被打印,因为 test1.py 中的不需要的 hello() 代码也被运行:

python test2.py
Hello

当然,您可以在 test2.py 中拨打 test1.hello():

# "test2.py"

import test1

test1.hello() # Here

然后,当运行测试2时,印刷了两个Hello:

python test2.py
Hello
Hello

现在,添加如果 __name__ ==“__main__”:测试1.py 并将 hello() 放在下面:

# "test1.py"

def hello()
    print("Hello")

if __name__ == "__main__":
    hello()

此分類上一篇: Test2.py:

# "test2.py"

import test1

test1.hello()

然后,在运行 test2.py 时,只有一个 Hello 被打印,因为如果 __name__ ==“__main__”:在 test2.py 输入 test1.py 时阻止运行不需要的 hello() 代码:

python test2.py
Hello

此外, test1.py 是否有 __name__ == “__main__”: 或者不:

# "test1.py"

def hello()
    print("Hello")

if __name__ == "__main__":
    hello()
# "test1.py"

def hello()
    print("Hello")

hello()

One Hello 在运行 test1.py 时正确打印:

python test1.py
Hello

当我们模块(M.py)中有某些声明时,我们希望当它作为主要(不进口)运行时,我们可以将这些声明(测试文件夹、印刷声明)置于此下,如果它被阻止。

默认情况下(当模块作为主运行时,不进口) __name__ 变量设置为“__main__”,当它被进口时, __name__ 变量将获得不同的值,最有可能是模块的名称(“M”)。

简而言之,使用这个“如果 __name__ ==“主””块,以防止(一定)代码在模块进口时运行。