2020-12-11 if __name__ == "__main__" in Python

Python中的 if __name__ == "__main__"

For Python beginners, they often see if __name__ == "__main__"it when they look at other people's code . At this time, I start to complain: "It's definitely a pretense. I don't write this sentence. The code doesn't still run well!

When I first encountered this line of code, I thought so in my heart!

Tucao returns to Tucao, there must be a reason for existence. Now let's take a look at what this code means, because this sentence can help you understand the Python module to a higher level.

Understand through examples

As long as you create a module (a .py file), the module will have a built-in attribute name generated, and the  value of the module's  name depends on how the module is applied. In other words, if you run the module directly, then __name__ == "__main__"; if you import a module,  the value of the module name is usually the module file name.

For example, create a test1.py:

def func():
    print('hello, world!')

if __name__ == "__main__":
    func()

In the module, the function func() is first defined to print hello, world!, and then it __name__ is judged whether it is equal  __main__, if it is equal, there is printing, otherwise, the opposite is true. Now run the module and the result is:

hello, world!

Description __name__ is equal to __main__ .

At this time, enter the code:

Create another test2.py:

import test1

print('bye, world!')

In the module, first import test1, then print bye, world! for testing purposes, run the module, the result is:

bye, world!

The operation result is only bye, world!, indicating that it is __name__ not equal to  __main__.

Through the two modules of test1.py and test2.py above, we can now draw a very practical conclusion:  if the module is run directly, the code block is run, and if the module is imported, the code block is not run.

Guess you like

Origin blog.csdn.net/qingfengxd1/article/details/111031358