在刚开始学习python时,经常会在其他作者的代码中看到 if __name__=="__main__"
。在查找各种博客后得出浅薄认识:
可以将__name__看作是当前模块的名字,那么这句代码的含义即是判断目前模块的名字是否与主程序的名字一致,举个例子:
# 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:
top-level in one.py
one.py is being run directly
当我们执行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
即可以看出,当运行one.py时,判定此时one.py没有被其他主程序导入模块,所以输出one.py is being run directly
当运行two.py,由于程序自上而下运行,会先运行one.py这个模块,此时one.py不是主程序,故输出one.py is being imported into another module
一般可以将此句作用于非主程序时隐藏语句使用。