__name__ 是当前模块名,当模块被直接运行时模块名为 __main__ 。这句话的意思就是,当模块被直接运行时,以下代码块将被运行,当模块是被导入时,代码块不被运行。编写私有化部分 ,这句代码以上的部分,可以被其它的调用,以下的部分只有这个文件自己可以看见,如果文件被调用了,其他人是无法看见私有化部分的.
# file one.py
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
# file two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
如果执行one.py文件:
python one.py
输出结果为:
top-level in one.py
one.py is being run directly
如果执行two.py文件:
python two.py
输出结果为:
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly