Python 解释器在读取 Python 文件时,会对一些特殊变量赋值,其中便有 __name__。
当 Python 文件作为主程序运行时,__name__ 被赋值为 __main__。例如,新建 foo.py 文件,代码如下:
# foo.py
print(f"foo's __name__ is set to: {__name__}")
执行上面的代码,得到如下结果:
foo's __name__ is set to: __main__
由于 foo.py 是作为主程序执行的,所以 foo.py 的 __name__ 被赋值为 __main__。
当 Python 文件作为一个模块被导入时,它的 __name__ 被赋值为文件名。例如,新建 bar.py 文件,并对 foo.py 进行修改,bar.py 和 foo.py 的内容如下:
# bar.py
print(f"bar's __name__ is set to: {__name__}")
# foo.py
import bar
print(f"foo's __name__ is set to: {__name__}")
执行 foo.py,得到如下结果:
bar's __name__ is set to: bar
foo's __name__ is set to: __main__
由于 bar.py 作为一个模块被导入,所以 bar.py 的 __name__ 被赋值为文件名 bar。
由于变量 __name__ 的上述特性,可以用来控制程序的执行,当 Python 文件作为主程序执行时,执行一部分代码;当 Python 文件作为一个模块被导入时,执行另外一部分代码。例如,修改 bar.py 和 foo.py,修改后的内容如下:
# foo.py
import bar
print(f"foo's __name__ is set to: {__name__}")
if __name__ == "__main__":
print("foo.py ran directly")
else:
print('foo.py ran imported')
# bar.py
print(f"bar's __name__ is set to: {__name__}")
if __name__ == "__main__":
print("bar.py ran directly")
else:
print('bar.py ran imported')
执行 foo.py 文件,输出结果如下:
bar's __name__ is set to: bar
bar.py ran imported
foo's __name__ is set to: __main__
foo.py ran directly
当执行 foo.py 时,由于 bar.py 是作为模块被导入的,所以 bar.py 的 __name__ 为 bar。而 foo.py 是直接执行的,所以 foo.py 的 __name__ 为 __main__ 。









