在Python中,为什么要这个东东 __name__ == __main__

本文介绍了Python中main函数的特性,即直接执行脚本时main函数会被调用,而脚本被导入其他脚本时main函数会被忽略。还阐述了其用途,如文件可作为模块被其他程序调用,也能作为主程序运行,还可用于单元测试、提供API等。

One of those nice features of Python, that marks it as a language designed for developers (as opposed to one designed for tool vendors) is the ability to conditionally run some logic if you’re executing a script directly but ignore it if the script is being imported (“included”) by another script.

python 的main 方法是个很有意思的东东,如果你直接执行这个带有main的脚本,它会被调用。但是当这个脚本被import到其他的脚本的时候,main 会被忽略掉。惊奇不惊奇。

 

Why Does It Work This Way? 要这个东东干啥呢

You might naturally wonder why anybody would want this. Well, sometimes you want to write a .pyfile that can be both used by other programs and modules as a module and can be run as the main program. 

也许你会本能的猜测为什么会有人想要这个,有时候你写一个.py文件,它可以被其他程序和模块调用,有可以作为主程序运行。

  • Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.

  • Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing .py files like your script and running special test functions. You don't want it to try running the script just because it's importing the module.

  • Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值