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

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

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


当前回答

如果此.py 文件是由其他.py 文件进口的,则如果声明下的代码将不会被执行。

如果这个.py 是由 python 运行这个_py.py 在 Shell 下, 或在 Windows 中双击, 该代码在 if 声明 下将执行。

通常是用来测试的。

其他回答

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

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

Python 主要功能是任何程序的起点. 当程序运行时,Python 翻译器连续运行代码. 主要功能只有当它作为 Python 程序运行时才运行。

def main():
    print("I am in the function")

print("I am out of the function")

当你运行脚本显示:

I am out of the function

而不是代码“我在职位”。

这是因为我们没有宣布呼叫函数“if__name__==“主”。

如果你使用它:

def main():
    print("I am in the function")

if __name__ == "__main__":
    main()

print("I am out of the function")

产量相当于

I am in the function
I am out of the function

在Python中,如果__name__==“__main__”允许您运行Python文件作为可重复使用的模块或单独的程序。

当Python 翻译器阅读源文件时,它将执行所有源文件中的代码;当Python 作为主程序运行“源文件”时,它设置了特殊变量 __name__ 以具有“__main__”值。

当您执行主函数时,它将读取如果声明,检查 __name__ 是否相当于 __main__。

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

在 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__ 不会执行。

如果 __name__ ==“__main__”:该怎么办?

__name__ 是一个全球变量(在 Python 中,全球实际上意味着在模块层面)存在于所有名称空间。

作为唯一的特殊情况,但是,在任何Python过程你运行,如 mycode.py:

python mycode.py

否则匿名的全球名称空间将“__main__”的值归咎于其 __name__。

因此,包括最后的线条

if __name__ == '__main__':
    main()

在您的 mycode.py 脚本的结尾,当它是由 Python 过程运行的主要输入点模块时,

将使您的脚本独特定义的主要功能运行。

使用此构造的另一个好处:您也可以将代码作为一个模块进口到另一个脚本,然后运行主功能,如果和当您的程序决定:

import mycode
# ... any amount of other code
mycode.main()