# 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 中的这种用法很灵活啊。