python 中的 if __name__=='__main__' 作用

先放代码:

one.py

#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")

three.py

#file three.py
def func1():
    print("func1() in three.py")

print("top-level in three.py")

if __name__ == "__main__":
    print("three.py is being run directly")
else:
    print("three.py is being imported into another module")

two.py

#file two.py
import one       
import tree
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")

调试结果:

➜  ~ python one.py
top-level in one.py
one.py is being run directly

➜  ~ python three.py
top-level in three.py
three.py is being run directly

➜  ~ python two.py
top-level in one.py
one.py is being imported into another module
top-level in three.py
three.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
有没有在two.py的运行结果中发现什么呢?

在python编译器读取源文件的时候会执行它找到的所有代码,而在执行之前会根据当前运行的模块是否为主程序而定义变量__name__的值为__main__还是模块名。因此,该判断语句为真的时候,说明当前运行的脚本为主程序,而非主程序所引用的一个模块。这在当你想要运行一些只有在将模块当做程序运行时而非当做模块引用时才执行的命令,只要将它们放到if __name__ == "__main__:"判断语句之后就可以了。


简而言之:在two.py中程序通过“import one”和“import three”,执行了one.py和three.py 的所有代码,但由于此时one,three只是主程序引入的一个模块,所以if __name__ == "__main__:"不成立,执行one.py,three.py 中的else语句,之后在返回主程序two.py。


若存在错误,请指出。谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值