1. Definition of main module and non-main module
In a Python function, if a function calls other functions to complete a function, we call this function the main function. If a function does not call other functions, we call this function a non-main function. The definitions of main modules and non-main modules are also similar. If a module is used directly without being called by others, we call this module the main module. If a module is called by others, we call this module a non-main module.
2. name attribute
In Python, there are main modules and non-main modules. Of course, we have to distinguish them. So how to distinguish between main modules and non-main modules?
This requires the use of the __name__ attribute. The --name—— attribute value is a variable, and this variable is given by the system. This variable can be used to determine whether a module is the main module. If the value of an attribute is __main__ , then this module is the main module, and vice versa. But please note: ** This __main__ attribute only helps us determine whether it is the main module. It does not mean that this attribute determines whether they are the main module. The condition for determining whether they are the main module is whether the module has been called. **
Look at the example specifically:
First create the module lname, and then determine whether it is the main module. If it is the main module, it will output main. If not, it will output not main. First Run the module directly. Since the module is used directly without being called, it is the main module, so main is output. See the figure below for details:
and then Create a user_lname module, which simply imports the lname module, and then executes it. The output result is not main, because the lname module is called by this module, so it is not the main module. The output result is as shown in the figure: