您现在的位置是:课程教程文章
Python中的__name__怎么用?
2023-12-18 23:49课程教程文章 人已围观
Python网络爬虫基础与实战
Python网络爬虫基础与实战蜗牛学院-专注中高端IT教育培训,只为成就更好的你! 咨询QQ:1964006600 电话:...
Python全栈精品课之Bootstrap(二)
Python全栈精品课之Bootstrap(二)...
赵越人工智能AI开发课(Python+PyCharm+PyTorc
赵越人工智能AI开发课(Python+PyCharm+PyTorc赵越人工智能AI开发课(Python+PyCharm+PyTorch) Python: 不用我多介绍了,已经是世界...
Python数据分析/突破职业天花板/机器学习
Python数据分析/突破职业天花板/机器学习...
Python中的__name__在Python中有两种用法:
1. 如果模块是被导入,__name__的值为模块名字
2. 如果模块是被直接执行,__name__的值为'__main__'

Py1.py
代码如下:
#!/usr/bin/env python def test(): print '__name__ = ',__name__ if __name__ == '__main__': test()
Py2.py
代码如下:
#!/usr/bin/env python import Py1.py def test(): print '__name__ = ',__name__ if __name__ == '__main__': test() print ‘Py1.py __name__ = ',Py1.__name__
执行结果:
代码如下:
__name__=__main__ Py1.py __name__=Py1
通过结果可以知道,Py2.py直接执行,那么内建变量__name__的值为__main__,否则为模块的名字,通过这个特性可以在if语句里面添加测试代码,可以提高减少BUG,提高程序的健壮性。
代码如下:
if __name__ == '__main__': test()课程教程:Python中的__name__怎么用?
下一篇:没有了