The __name__ attribute in python is a special variable:
1. __n name__ is a variable. The double underscores are added before and after because this is a system-defined name. Ordinary variables do not name variables this way.
2. Python has many modules, and these modules can run independently! This is not like C++ and C header files.
3. When importing, it is necessary to execute the imported module.
4. __name__ is a system variable that identifies the name of the module. There are two cases here: if the current module is the main module (that is, the module that calls other modules), then the name of this module is __main__, and the main function content after "__mian__:" can be executed by judging by if; if this module is If it is imported, the module name is the file name (without the following .py), and the content after "__mian__:" will be skipped by judging by if.
Through the above method, python can distinguish which are the main functions, enter the main function execution; and can call various functions of other modules and so on.
example:
# -*- coding: utf-8 -*- ' a test module ' # Documentation comments are accessible via __doc__ __author__ = 'frala' #author notes import sys def test(): args = sys.argv if len(args)==1: print ('Hello world!') elif len(args)==2: print ('Hello,%s' % args[1]) else: print ('Too many arguments!') if __name__ == '__main__': test()Since this program is the main program, once executed
Because __name__ == '__main__', enter if, so the test function will be executed.
import hello print (hello.__name__)
Now __name__=='hello' in the hello module, not '__main__' anymore.
So the hello module does not enter the if statement.