[Reserved] python in if name == 'main': the role and principles

python, IF name == ' main ': the role and principles

Find useful, welcome to discuss mutual learning together - Follow Me

A python files typically used in two ways, first as a script is executed directly, and the second is to import another python script is called (block reuse) performed. Thus IF name == 'main': the role of these two cases is to control execution of the code of the process, the IF name == 'main': under the code only (i.e., as a script file direct execution) only in the first case It will be executed, and import to other scripts will not be executed. Examples are as follows:

  • Direct execution
    Here Insert Picture Description
    direct execution test.pyresults as shown below, can successfully print two lines of character strings. That is, IF name == " main ": the code before and after the statements are executed.
    Here Insert Picture Description
  • import performed
    then the new folder name in the same script file import_test.py, enter the following code:
    Here Insert Picture Description
    execution import_test.py script, the following output:
    Here Insert Picture Description
    output only the first line of the character string. That is, IF name == " main ": before the statement is executed, not executed after.

the reason

  • This is because each file has a __name__variable, in test.py file, if executed directly, __name__that is test.py, if the implementation is the test in another file.
  • And each file has a __main__constant, this constant value at all times to test.py, namely the file name + .py
  • Further when the module is executed directly, name == 'main' is true.
    To further illustrate, we in test.pyif the script name == " main ": Prior to joining Print ( name ), is about to name printed. File contents and results are as follows:
    Here Insert Picture Description
    Here Insert Picture Description
    As can be seen, when the value of the variable __name__ " main ."
    Then execute import_test.py, execution results are as follows:
    Here Insert Picture Description
    Here Insert Picture Description

At this time, in the test.py Test __name__ variable value, does not satisfy name == " main condition", therefore, can not execute the subsequent code.

Guess you like

Origin www.cnblogs.com/cloud-ken/p/12629181.html