码迷,mamicode.com
首页 > 编程语言 > 详细

关于Python中的 if __name__ == '__main__'

时间:2018-05-16 15:22:25      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:nal   https   set   bsp   col   lib   anon   ==   cond   

官方文档对于"__main__"的回答(ref: https://docs.python.org/2/library/__main__.html):

This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt. It is this environment in which the idiomatic “conditional script” stanza causes a script to run:
if __name__ == "__main__":
    main()

也就是说,当解释器的主项目执行的时候,使用__main__来指示代码的执行范围。执行主项目的命令可以来自标准输入(python xxx.py),脚本文件等

stackoverflow的回答如下(ref:https://stackoverflow.com/questions/419163/what-does-if-name-main-do):

对于__name__的解释:

For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the modules name.

为什么要这样设计的原因:

One reason for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.

 

关于Python中的 if __name__ == '__main__'

标签:nal   https   set   bsp   col   lib   anon   ==   cond   

原文地址:https://www.cnblogs.com/geeklove01/p/9045530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!