This article mainly introduces Python if __name__ = = ' __main__ ' function parsing, which is very common in Python, does it work? This article has analyzed its function, needs the friend to be possible to refer to under
When you open a. py file, you will often see the if __name__ = = ' __main__ ' at the bottom of the code: Now let's introduce its role.
The module is an object, and all modules have a built-in attribute __name__. The value of a module's __name__ depends on how you apply the module. If you import a module, the module __name__ value is usually the module file name, without the path or file name extension. But you can also run the module like a standard program sample directly, in which case the __name__ value will be a special default "__main__".
///////////////////////////////////////////////////////////////////////////////////////////////////
Run the. py file directly in cmd, the value of __name__ is ' __main__ ';
When you import a. py file, the value of the __name__ is not ' __main__ ';
Then use if __name__ = = ' __main__ ' to determine if the. py file is being run directly
Such as:
The code is as follows:
#Test. py
Class Test:
def __init (self):p
def f (self):p rint ' Hello, world! '
if __name__ = = ' __main__ ':
Test (). F ()
#End
You enter in cmd:
The code is as follows:
C:>python test.py
Hello, world!.
Description: "__name__ = = ' __main__ '" is established
You enter in cmd again:
The code is as follows:
C:>python
>>>import Test
>>>test.__name__ #Test模块的__name__
' Test '
>>>__name__ #当前程序的__name__
' __main__ '
No matter how, test.py in the "__name__ = = ' __main__ '" will not set up!
So the next line of code never runs to!