【Python】浅析模块的__name__

博主在刚开始学习python时候,经常看到python脚本的最后部分会去执行 if __name__ == '__main__'这个判断,但是添加这个判断到底有什么作用博主并不知情。

在python当中是有模块的概念的,每个模块都有一个自己的名称,可以通过模块内置的__name__属性来得到模块的名称。而模块的名称又取决于python模块的使用的方式,因为模块既可以自己直接执行,也可以导入到别的模块当中使用。

我这里用代码举个例子:

#!/usr/bin/python
# Filename: pylocal.py

def showName():
    print("The name of module is", __name__)


if __name__ == '__main__':
    print('pylocal.py is being run by itself')
    showName()
else:
    print('pylocal.py is being imported into another module')
    showName()
#!/usr/bin/python
# Filename: pyother.py

from pylocal import showName

if __name__ == '__main__':
    print('pyother.py is being run by itself')
    showName()
else:
    print('pyother.py is being imported into another module')
    showName()

这里我在pylocal.py这个模块当中定义了一个名为showName的函数,同时在两个模块当中分别加入了if __name__ == '__main__'这个判断,与此同时pyother.py模块中对pylocal.py做了一次导入操作。

当运行pylocal.py模块的时候,其运行结果如下:

pylocal.py is being run by itself
The name of module is __main__

当运行pyother.py模块的时候,其运行结果如下:

pylocal.py is being imported into another module
The name of module is pylocal
pyother.py is being run by itself
The name of module is pylocal

我们可以看到如下情况:

  • pylocal.py模块直接运行时,这个模块的__name__值就是'__main__'
  • pylocal.py模块被pyother.py模块调用的时候,那么这个模块(也就是pylocal.py模块)的__name__的值就是该模块的文件名(不带文件路径和文件的扩展名),即pylocal

同时,我们也看到了模块在被其他模块导入的过程当中也执行了一次。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值