前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 关于 name main的使用 if __name__ == '__main__':

Python 关于 name main的使用 if __name__ == '__main__':

作者头像
bear_fish
发布2018-09-20 14:55:19
1.6K0
发布2018-09-20 14:55:19
举报
文章被收录于专栏:用户2442861的专栏

看过很多python的code都有这段代码:

1 2

if __name__ == '__main__':     statements

这段代码的主要作用主要是让该python文件既可以独立运行,也可以当做模块导入到其他文件。当导入到其他的脚本文件的时候,此时__name__的名字其实是导入模块的名字,不是'__main__', main代码里面的就不执行了。

比如有这样的一个文件test.py, 里面代码如下:

1 2 3 4 5 6 7

# test.py   def test():     print("Test function.")   if __name__ == '__main__':     test()

 当按F5的时候可以独立运行程序,结果:

1 2 3

>>> ================================ RESTART ================================ >>> Test function.<br>>>> print(__name__)<br>__main__<br>>>>

 但是也可以作为模块import使用,结果:

1 2 3 4 5

>>> import test >>> test.test <function test at 0x0000000003455F28> >>> test.test() Test function.

代码语言:javascript
复制
参考:
代码语言:javascript
复制
http://pyfaq.infogami.com/tutor-what-is-if-name-main-for
代码语言:javascript
复制

The if __name__ == "__main__": ... trick exists in Python so that our Python files can act as either reusable modules, or as standalone programs. As a toy example, let's say that we have two files:

mumak:~ dyoo$ cat mymath.py

mymath.py文件

1 2 3 4 5

def square(x):     return x * x   if __name__ == '__main__':     print "test: square(42) ==", square(42)

mumak:~ dyoo$ cat mygame.py

mygame.py 文件

1 2 3 4 5

import mymath   print "this is mygame."   print mymath.square(17)

In this example, we've written mymath.py to be both used as a utility module, as well as a standalone program. We can run mymath standalone by doing this:

代码语言:javascript
复制
mumak:~ dyoo$ python mymath.py
test: square(42) == 1764

But we can also use mymath.py as a module; let's see what happens when we run mygame.py:

代码语言:javascript
复制
mumak:~ dyoo$ python mygame.py
this is mygame.
289

Notice that here we don't see the 'test' line that mymath.py had near the bottom of its code. That's because, in this context, mymath is not the main program. That's what the if __name__ == "__main__": ... trick is used for.

在这个例子里面mygame.py里面调用square函数的时候,就不会执行mymath.py里面的main函数了。

伪python爱好者,正宗测试实践者。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015年04月10日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档