Since there is no main() function in Python, when the command to run a python program is given to the interpreter, the code with level 0 indentation will be executed. However, before doing this, it will define some special variables; __name__ is one such special variable. In this article, I will introduce you to the special variable __name__. I hope it will be helpful to you.
#__name__ is a built-in variable that evaluates to the name of the current module. If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value of "__main__"; if this file is imported from another module, __name__ is set to the name of the module.
Therefore, it can be used to check whether the current script is run alone or imported elsewhere by combining it with an if statement.
Let’s learn about it through an example:
There are two separate files File1 and File2.
File1.py
print "File1 __name__ = %s" %__name__ if __name__ == "__main__": print "File1正在直接运行" else: print "File1正在导入"
File2.py
import File1 print "File2 __name__ = %s" %__name__ if __name__ == "__main__": print "File2正在直接运行" else: print "File2正在导入"
Now, the interpreter is given the command to run File1.py.
python File1.py
Then, the output:
File1 __name__ = __main__ File1正在直接运行
Then run File2.py.
python File2.py
The output:
File1 __name__ = File1 正在导入File1 File2 __name__ = __main__ File2正在直接运行
As shown above, when running File1.py directly , the interpreter sets the __name__ variable to __main__, and when file2.py is run through the import, the __name__ variable is set to the name of the python script, which is File1. So let's say __name__ == "__main__" is the part of the program that runs when you run the script from the command line using something like python File1.py.
Recommended video tutorials: "Python Tutorial"
The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of What is the use of the special variable __name__ in Python?. For more information, please follow other related articles on the PHP Chinese website!