if __name__ == 'main': 的作用和原理

if __name__ == 'main':

功能


一个python的文件有两种使用的方法,第一是直接作为脚本执行,第二是import到其他的python脚本中被调用(模块重用)执行。

if __name__ == 'main': 的作用:

就是控制这两种情况执行代码的过程,在“if __name__ == 'main': ”下的代码只有在第一种情况下(即文件作为脚本直接执行)才会被执行,而import到其他脚本中是不会被执行的

原理


 每个python模块(python文件,也就是*.py)都包含内置的变量__name__。

1. 当运行模块(A.py)作为脚本自己去运行的话,对应的模块名始终叫做__main__,即模块A.py文件本身,而__name__等于模块名称,也就等于__main__;

2. 如果模块(A.py)import到其他模块(B.py)中,对应的模块名叫做A,则__name__等于模块名称A。

所以,当模块被直接执行时,__name__ == '__main__'结果为真;当模块被import到其他的python脚本中被调用执行,不满足__name__=="__main__"的条件,因此,无法执行其后的代码。

test.py

print("I'm the first.")
print(__name__)
if __name__=="__main__":
     print("I'm the second.")

python test.py的结果:

I'm the first.
__main__
I'm the second.

import_test.py

import test

python import_test.py的结果:

I'm the first.
test

此时,test.py中的__name__变量值为test,不满足__name__=="__main__"的条件,因此,无法执行其后的代码。

__name__


如果是放在Modules模块中,就表示是模块的名字;

如果是放在Classs类中,就表示类的名字

__main__


模块第一次被导出(import)后,系统会自动为其创建一个域名空间(namespace);(模块,都是有自己的名字的)此处的脚本的主模块的名字,始终都叫做__main__。

【参考文档】

python编程中的if __name__ == 'main': 的作用和原理:http://www.dengfeilong.com/post/60.html

Python中的__name__和__main__含义详解:https://blog.csdn.net/jjwen/article/details/53084882

Python中的__name__和__main__含义详解: https://www.crifan.com/python_detailed_explain_about___name___and___main__/comment-page-1/

原文地址:https://www.cnblogs.com/chenyuting/p/9322690.html