Home » Python » Python if __name__ = ' __main__': analysis;

Python if __name__ = ' __main__': analysis;

When you open a.Py file, often at the bottom of the code to see if __name__ = ='__main__': now, to introduce the role of the.

Module is the object, and all the modules have a built-in __name__. value depends on the attributes of a module __name__ to you how to apply. If a module import module, then __name__ module is usually module file name, without a path or file name extension. But you can also like a standard program direct operation module, in this case, the value of __name__ will be a special default "__main__".


Run the.Py file directly in CMD, and the value of __name__ is'__main__';

In import, after a.Py file, the value of __name__ is not'__main__';

To use if __name__ = ='__main__'to determine whether it is in the direct operation of the.Py file

Such as:


Class Test:

Def __init (self): pass #pass is written to maintain code integrity, without any effect, do, nothing

Def, f (self): print,'Hello, World,'

If __name__:


Test ().F ()


You type in CMD:

C:>python Test.py

Hello, World,


Note: "__name__ ='__main__'" is established

You enter again in CMD:


>>>import Test

The __name__

of the >>>Test.__name__ #Test module


>>>__name__ # current program __name__


No matter what, in Test.py "__name__ ='__main__'" are not set up


So the next line of code never runs until