Understanding of "if `__name__`==`__main__`:" in Python

When we use C\CPP and Java programming, we will write a main function, which is the entrance to the program execution code.

int main(){
    
    
    printf("Helloworld");
}

As an interpreted scripting language, Python does not need a main function as the entry point of the program , but translates and executes it line by line from the top line of the py file. From this point of view, "if __name__== __main__:" seems to have a certain symbolic nature, letting people who read the code know that this is the entry point of the program. But it __name__is actually a built-in attribute of Python.

__name__The meaning of the attribute

__name__The attribute is a built-in attribute of Python that records a string.

There are two possibilities for the content on this string:

①The file name of the module file

__main__

For example, there is now a hello.py file:

When we import hello in other files, it hello.__name__==“hello”is True.

If we run hello.py directly, it hello.__name__==“__main__”is True.

if __name__==__main__:The role of " ":

Once you understand the __name__meaning of the attribute, you can use it to program.

If some code in the module only needs to be executed when the module is directly run, and does not need to be executed when imported, then we only need to:

if __name__==__main__:
    lineA
    lineB
    lineC

Guess you like

Origin blog.csdn.net/weixin_51447314/article/details/114082050