When you open a. py file, you will often see 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 property of __name__. The value of the __name__ of a module depends on how you apply the module. If you import a module, the value of the module __name__ is usually the module file name, without the path or file extension. But you can also run the module directly like a standard program, in which case the __name__ value will be a special default "__main__".
///////////////////////////////////////////////////////////////////////////////////////////////////
Run the. py file directly in cmd, then the value of __name__ is ' __main__ ';
After import a. py file, the value of __name__ is not ' __main__ ';
Thus use if __name__ = = ' __main__ ' to determine whether the. py file is running directly
Such as:
#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:
C:>python test.py
Hello, world!.
Description: "__name__ = = ' __main__ '" is established
You type in cmd again:
C:>python
>>>import Test
>>>test.__name__ #Test模块的__name__
' Test '
>>>__name__ #当前程序的__name__
' __main__ '
No matter what, test.py in the "__name__ = = ' __main__ '" will not be set up!
So, the next line of code will never run to!
//////////////////////////////////////////////////////////////////////////////////
Python-based python if __name__ = = ' __main__ ': parsing