经常在 .py
脚本文件中看到这么一句: if __name__ == '__main__':
,那么这句声明到底代表什么?又发挥着什么作用呢?
一、介绍
Python
程序不同于其他语言,文件自上而下执行。
- 作用
添加这段代码的作用是让该 Python
文件既可以独立运行,也可以当做模块导入到其他文件。
当导入到其他的脚本文件的时候,此时 __name__
的名字其实是导入模块的名字,不是 __main__
,因此 main
中的代码便不会执行。
- 实例测试
新建一个测试文件 test_main.py
如下:
def fun():
print("This is function.")
if __name__ == '__main__':
fun()
print("This is main function.")
''''
C:> python test_main.py
This is function.
This is main function.
'''
将 test_main.py
作为模块导入,并执行测试。
import os
os.chdir(r"C:UsersHiderDesktop est")
import test_main as tm
tm.fun()
'''
This is function.
'''
__main__
模块中的代码并未执行。
二、全局内置变量
__name__
存储当前py文件调用方法的方法名。
# 直接运行
def fun():
print("This is function.")
def print_name():
print('__name__的值是:', __name__)
if __name__ == '__main__':
fun()
print_name()
print("This is main function.")
'''
This is function.
__name__的值是: __main__
This is main function.
'''
# 作为导入
import os
os.chdir(r"C:UsersHiderDesktop est")
import test_main as tm
tm.fun()
tm.print_name()
'''
This is function.
__name__的值是: test_main
'''
参考链接1:Python中
'__main__'
模块的作用