Python 主函数

正如你所知道的,我们也可以 import一个 python 程序作为一个模块,在这种情况下,python 主要方法不应该执行。

Python 主要功能

主函数是任何程序的入口点,但是Python解释器会连续执行源文件代码,如果它不是代码的一部分,就不会调用任何方法,但是如果它直接是代码的一部分,那么当文件被导入为模块时,它会被执行,这就是为什么在Python程序中有一个特殊的技术来定义主方法,这样它只能在直接运行时执行,而不是导入为模块时执行。

1print("Hello")
2
3print("__name__ value: ", __name__)
4
5def main():
6    print("python main function")
7
8if __name__ == '__main__':
9    main()

它还设置了少数默认的变量值,其中一个为__name__,其值设置为__main__ *对于 Python 主函数,我们必须定义一个 函数的代码,然后使用if __name__ == '__main__'的条件来执行这个函数 *如果 Python 源文件被导入为 [模块](/community/tutorials/python-modules),那么 python 解释器会为模块名称定义__name/tutorials/python-function-arguments`的值,所以如果返回错误和主方法,则将不会执行条件

  • 如果主函

Below image shows the output when python_main_function.py is executed as source file. python main function, python if name main

Python 主函数作为模块

现在让我们用上面的 python 源文件作为一个模块,并在另一个程序中导入。

1import python_main_function
2
3print("Done")

Now when above program is executed, below output is produced. python main method, python if main

1Hello
2__name__ value:  python_main_function
3Done

请注意,前两行是从「python_main_function.py」源文件中打印的。 请注意「name」的值是不同的,因此主方法不执行。 请注意,python程序的陈述是沿线执行的,所以在执行主方法的 if 条件之前首先定义主()方法很重要。

Published At
Categories with 技术
Tagged with
comments powered by Disqus