if __name__ == '__main__'的含义

当打开工程下的一个.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__':下面的语句或者函数.

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值