python if __name__==“__main__“的含义

在刚开始学习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

一般可以将此句作用于非主程序时隐藏语句使用。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值