版权声明:找不到大腿的时候,让自己变成大腿. https://blog.csdn.net/Xin_101/article/details/86533993
1 起因
程序看多了,发现定义类,函数之后,执行是都与if __name__ == "__main__"
,百撕不得qi解,一怒之下,查了资料,总结如下.
2 从__name__
说起
2.1 小例-1
- Demo
新建文件test.py
def output_name():
print("Name: {}".format("xindaqi"))
output_name()
print(__name__)
- Result
xindaqi
__main__
- Analysis
在当前*.py文件中,__name__
值为__main__
2.2 小例-2
- Demo
test.py
def output_name():
print("Name: {}".format("xindaqi"))
output_name()
print(__name__)
main_test.py
import test
def output_job():
print("Job: {}".format("AI Engineer"))
output_job()
print(__name__)
- Result
Name: xindaqi
test
Job: AI Engineer
__main__
- Analysis
- 通过
import
导入*.py文件,如test.py
导入到main_test.py
,执行main_test.py
,输出的结果包括文件test.py
,main_test.py
的输出; - 在
main_test.py
中输出test.py
的__name__
为test.py
的文件(模块)名test
;
这就催生了if __name__ == "__main__"
- 每一个模块或
*.py
文件都有__name__
,在本模块中,__name__
为__main__
,被引入到其模块中,__name__
为模块名. - 为使每次只执行主文件中的函数,可用
__name__
进行函数隔离.
2.3 小例-3
- Demo
test.py
def output_name():
print("Name: {}".format("xindaqi"))
# 隔离函数执行
if __name__ == "__main__":
output_name()
print(__name__)
main_test.py
import test
def output_job():
print("Job: {}".format("AI Engineer"))
output_job()
print(__name__)
- Result
Job: AI Engineer
__main__
- Analysis
- 在
test.py
中,使用了判断__name__
决定是否执行函数,因为在main_test.py
中,__name__
值为__main__
,所以只执行了main_test.py
中的函数; __name__
隔离了被引用模块的函数执行;
3 总结
__name__
是*.py
的内置函数,即每个文件都有__name__
,在本文件中__name__
值为__main__
,在引入的文件中,__name__
为模块名称;- 通过
if __name__ == "__main__"
隔离被引用模块的函数执行,只引入模块;
[参考文献]
[1]http://blog.konghy.cn/2017/04/24/python-entry-program/