当打开工程下的一个.py文件时,经常会在代码的最下面看到if __name__ == '__main__':,那么这个到底是什么意思呢?
假设我们有这样一个test.py文件
#test.py
print('import the module')
def main():
print('Hello, World!')
if __name__ == '__main__':
main()
#end
1.首先直接运行test.py,在CMD中输入python test.py:
>>>python test.py
import the module
Hello, World!
同时输出了'import the module'和'Hello, World!’
说明:__name__ == '__main__'是成立的,所以执行了下面的main()
2.接下来请我们用import的方式,在CMD中输入python,再输入import test
>>>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>import test
import the module #只输出了这个,没有Hello, World!
#这个时候
>>>test.__name__
'test'
>>>__name__
'__main__'
只输出了'import the module',没有输出'Hello, World!'
可以看出这个时候test模块的__name__='test'
而当前程序的__name__='__main__'
无论怎样,test.py中的__name__ == '__main__'都不会成立的,也就意味着,当你是通过import的方法来执行这个.py文件时,不能运行if __name__ == '__main__':下面的语句或者函数.
本文详细解析了Python中if __name__ == '__main__':语句的作用,通过实例演示了该语句如何区分直接运行与导入模块的不同行为,帮助读者深入理解这一关键语法。
6252

被折叠的 条评论
为什么被折叠?



