频道栏目
首页 > 程序开发 > Web开发 > Python > 正文
Python 关于 name main的使用
2012-07-19 13:59:18           
收藏   我要投稿

__name__:

在使用自身的时候,就是main,比如你执行:
python test.py
此时在test.py里面的name就是main
如果你在test2中import test,那么name就是文件名https://www.cnblogs.com/herbert/archive/2011/09/27/2193482.html

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

if __name__ == '__main__':这段代码的主要作用主要是让该python文件既可以独立运行,也可以当做模块导入到其他文件。当导入到其他的脚本文件的时候,该main代码里面的就不执行了。参考:https://pyfaq.infogami.com/tutor-what-is-if-name-main-for 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
def square(x):
    return x * x

if __name__ == '__main__':
    print "test: square(42) ==", square(42)


mumak:~ dyoo$ cat mygame.py
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:

mumak:~ dyoo$ python mymath.py
test: square(42) == 1764But we can also use mymath.py as a module; let's see what happens when we run mygame.py:

mumak:~ dyoo$ python mygame.py
this is mygame.
289Notice 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函数了。

点击复制链接 与好友分享!回本站首页
相关TAG标签
上一篇:python学习笔记之wxpython打印预览
下一篇:python判断对象是否为文件对象(file object)
相关文章
图文推荐
点击排行

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站