【转载】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 中的这种用法很灵活啊。



目录
打赏
0
0
0
0
34
分享
相关文章
|
2月前
|
如何简单地理解Python中的if __name__ == '__main__'
本文介绍了Python中`__name__ == '__main__'`的作用和原理,解释了它如何作为程序入口控制代码执行。当.py文件直接运行时,`if __name__ == '__main__'`下的代码块会被执行;而当文件作为模块被导入时,该代码块不会执行。此外,文章还探讨了`__name__`变量在包结构中的作用,以及`__main__.py`文件与`python -m`命令的关系,详细说明了不同运行方式对模块路径的影响。
126 18
|
9月前
|
【Python】 已解决:NameError: name ‘python‘ is not defined
【Python】 已解决:NameError: name ‘python‘ is not defined
1075 8
【Python】已完美解决:ImportError: cannot import name ‘Imputer‘ from ‘sklearn.preprocessing
【Python】已完美解决:ImportError: cannot import name ‘Imputer‘ from ‘sklearn.preprocessing
632 3
5-5|python开启多线程入口必须在main,从python线程(而不是main线程)启动pyQt线程有什么坏处?...
5-5|python开启多线程入口必须在main,从python线程(而不是main线程)启动pyQt线程有什么坏处?...
Python控制流:条件语句(if, elif, else)
本文详细介绍了Python条件语句的使用方法,包括if、elif和else,以及条件表达式和多条件判断。通过一个综合详细的例子,我们展示了条件语句在实际编程中的应用。希望本文对您理解和应用Python条件语句有所帮助。
【Azure Developer】Python 获取 Azure 中订阅(subscription)信息,包含ID, Name等
【Azure Developer】Python 获取 Azure 中订阅(subscription)信息,包含ID, Name等
105 0
|
10月前
|
python中模块对象__name__
【6月更文挑战第12天】
159 7
【Python】已解决:(最新版selenium框架元素定位报错)NameError: name ‘By’ is not defined
【Python】已解决:(最新版selenium框架元素定位报错)NameError: name ‘By’ is not defined
290 0
|
9月前
|
【Python】已解决:(pandas读取DataFrame列报错)raise KeyError(key) from err KeyError: (‘name‘, ‘age‘)
【Python】已解决:(pandas读取DataFrame列报错)raise KeyError(key) from err KeyError: (‘name‘, ‘age‘)
798 0
|
9月前
|
【Python】已解决:NameError: name ‘reload’ is not defined
【Python】已解决:NameError: name ‘reload’ is not defined
439 0

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等