[英]do I have to have main function in my python code?
Can I write a python code with a bunch of functions but without a main function. 我可以用一堆函数编写一个python代码但没有main函数。 The purpose of this script is for other scripts to import some of the functions from. 此脚本的目的是为其他脚本导入一些函数。 I will call it setvar_general.py or something which will be imported by a series of other setvar_x scripts. 我将其称为setvar_general.py或将由一系列其他setvar_x脚本导入的内容。 While these setvar_x do more specific things, setvar_general does not do any thing other than providing building blocks. 虽然这些setvar_x执行更具体的操作,但setvar_general除了提供构建块之外不会做任何事情。 Therefore there is not need for defining a main function in setvar_general.py. 因此,不需要在setvar_general.py中定义main函数。
I guess it all comes down to the question "do I have to have main function"? 我想这一切都归结为“我必须拥有主要功能”的问题吗?
You do not have to have a main function in Python and writing separate files without a main function, to be imported into other programs, is the normal and correct way of doing Python programming. 您不必在Python中使用main函数并且在没有 main函数的情况下编写单独的文件,以便导入到其他程序中,这是执行Python编程的正常和正确的方法。
When a Python file is loaded (either using import
or by getting executed from the command line) each statement in the program is executed at that time . 当一个Python文件被加载(使用import
或通过在命令行获取执行)程序中的每个语句在该时间执行。 Statements that are def
or class
statements create a function or class definition for later use. def
或class
语句的语句创建函数或类定义供以后使用。 Statements that are are not inside a def
or class
will be executed right away. 不在def
或class
语句将立即执行。
Therefore, the equivalent of a main()
function in other languages is actually the set of executable statements found in your file. 因此,在其他语言中等效的main()
函数实际上是在您的文件中找到的可执行语句集。 If you limit these to def
and/or class
statements, you will get the effect you want. 如果将这些限制为def
和/或class
语句,您将获得所需的效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.