if __name__ == "__main__": the role and principle

There are usually two ways to use a python file:

(1) Executed directly as a script,

(2) import to other python scripts to be called (module reuse) for execution.

Each python module (python file, that is, main.py and demo2.py here) contains a built-in variable __name__, when the module is executed directly, __name__ is equal to the file name (including the suffix .py); if If the module is imported into other modules, the __name__ of the module is equal to the module name (without the suffix .py). And "__main__" always refers to the name of the currently executing module (including the suffix .py). Thus, __name__ == 'main' evaluates to true when the module is executed directly.

Therefore, the role of if __name__ == 'main': is to control the process of executing code in the first two cases. The code under if __name__ == 'main': will only be executed in the first case, and import to other scripts will not be executed.

Examples are as follows:

I. Direct execution

Create a new script named demo2.py in the folder, and write the following code in demo2.py:

# 文件:demo2.py
print('Hello World!')
if __name__ == '__main__':
    print('World Record')

Output, two lines of strings can be successfully output:

Hello World!
World Record

2. import import operation:

Import the previous demo2 in main.py:

import demo2

output:

Hello World!

Only the first line of string is output. That is, if __name__=="__main__": The previous statement is executed, and the subsequent statement is not executed.

Guess you like

Origin blog.csdn.net/qq_54708219/article/details/129324454