【转载】Python 中 if __name__ == '__main__': 的作用

简介:

# hello.py 

?
1
2
3
4
5
6
7
def sayHello():
     str = " hello "
     print ( str );
 
if __name__ = = " __main__ " :
     print ( ' This is main of module "hello.py" ' )
     sayHello()

      python 作为一种脚本语言,我们用 python 写的各个 module 都可以包含以上那么一个类似 c 中的 main 函数,只不过 python 中的这种 __main__ 与 c 中有一些区别,主要体现在:

1、当单独执行该 module 时,比如单独执行以上 hello.py,则输出

?
1
2
3
# python hello.py
This is main of module " hello.py " 
hello

可以理解为"if __name__=="__main__":" 这一句与c中的main()函数所表述的是一致的,即作为入口;

2、当该 module 被其它 module 引入使用时,其中的 if __name__=="__main__": 所表示的 Block 不会被执行,这是因为此时 module 被其它 module 引用时,其 __name__ 的值将发生变化,__name__ 的值将会是 module 的名字。比如在 python shell 中执行 import hello 后,查看hello.__name__ 的值,可以看到:

?
1
2
3
4
>>> import hello
>>> hello. __name__
' hello '
>>>

      因此,在 python 中,当一个 module 作为整体被执行时,moduel.__name__ 的值将是 "__main__";而当一个 module 被其它 module 引用时,module.__name__ 将是 module 自己的名字,当然一个 module 被其它 module 引用时,其本身并不需要一个可执行的入口 main 了。可以说python 中的这种用法很灵活啊。



目录
相关文章
|
2月前
|
Python
python中if语句(二)
python中if语句(二)
21 0
|
2月前
|
Python
python中if语句(一)
python中if语句(一)
25 0
|
2月前
|
Python
Python中 If语句条件测试
Python中 If语句条件测试
21 1
|
4月前
|
Python
python RuntimeError: main thread is not in main loop
python RuntimeError: main thread is not in main loop
80 1
|
4月前
|
Python
Python if语句
Python if语句
|
2天前
|
Python
【Python操作基础】——if语句用法
【Python操作基础】——if语句用法
|
2月前
|
Python
python中if __name__ == '__main__'
python中if __name__ == '__main__'
17 3
|
2月前
|
Python
python中if语句(三)
python中if语句(三)
12 0
|
2月前
|
Python
Python中如何使用if语句处理列表
Python中如何使用if语句处理列表
36 1
|
2月前
|
Python
Python使用if语句处理列表及如何使用列表推导式来创建一个新列表
Python使用if语句处理列表及如何使用列表推导式来创建一个新列表
30 0