Python中if __name__ == '__main__':作用

简介: #hello.pydef sayHello(): str="hello"print(str);if__name__=="__main__":print ('This is main of module "hello.

#hello.py
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: 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__:

>>> import hello
>>> hello. __name__
' hello '
>>>

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

作者:Bonker
出处:http://www.cnblogs.com/Bonker
QQ:519841366
       
本页版权归作者和博客园所有,欢迎转载,但未经作者同意必须保留此段声明, 且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利
目录
相关文章
|
1月前
|
Python
python中if语句(二)
python中if语句(二)
20 0
|
1月前
|
Python
python中if语句(一)
python中if语句(一)
19 0
|
1月前
|
Python
Python中 If语句条件测试
Python中 If语句条件测试
21 1
|
3月前
|
Python
python RuntimeError: main thread is not in main loop
python RuntimeError: main thread is not in main loop
67 1
|
3月前
|
Python
Python if语句
Python if语句
|
1月前
|
Python
python中if __name__ == '__main__'
python中if __name__ == '__main__'
17 3
|
1月前
|
Python
python中if语句(三)
python中if语句(三)
12 0
|
1月前
|
Python
Python中如何使用if语句处理列表
Python中如何使用if语句处理列表
20 1
|
1月前
|
Python
Python使用if语句处理列表及如何使用列表推导式来创建一个新列表
Python使用if语句处理列表及如何使用列表推导式来创建一个新列表
24 0
|
1月前
|
Java C++ Python
Python分支结构内联if讲解
Python分支结构内联if讲解
16 0