Analysis of if _ name _ = '_ main _' in Python
This article mainly introduces the function of if _ name _ = '_ main _' in Python, which is very common in Python and plays a role? This article explains its role. For more information, see
When you open. in The py file, if _ name _ = '_ main _' is often displayed at the bottom of the Code. Now let's introduce its role.
A module is an object, and all modules have a built-in attribute _ name __. The value of _ name _ of a module depends on how you apply the module. If you import a module, the value of module _ name _ is usually the module file name, without the path or file extension. However, you can run a module directly like a standard program. In this case, the value of _ name _ is a special default value "_ main __".
//////////////////////////////////////// //////////////////////////////////////// ///////////////////
Run the. py file directly in cmd, and the value of _ name _ is '_ main __';
After importing a. py file, the value of __name _ Is Not '_ main;
Therefore, if _ name _ = '_ main _' is used to determine whether the. py file is directly running.
For example:
The Code is as follows:
# Test. py
Class Test:
Def _ init (self): pass
Def f (self): print 'hello, World! '
If _ name _ = '_ main __':
Test (). f ()
# End
In cmd, enter:
The Code is as follows:
C:> python Test. py
Hello, World!
Note: "_ name _ = '_ main _'" is true.
In cmd, enter:
The Code is as follows:
C:> python
>>> Import Test
>>> Test. _ name _ # Test module's _ name __
'Test'
>>>__ Name _ # current program's _ name __
'_ Main __'
In any case, "_ name _ = '_ main _'" In Test. py will not be true!
Therefore, the next line of code will never run!