Python中__name__的使用实例

WBOY
Release: 2016-06-06 11:25:30
Original
1161 people have browsed it

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()

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!