[转帖]Python 关于 name main的使用_Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 3026 | 回复: 0   主题: [转帖]Python 关于 name main的使用        下一篇 
lijia.peng
注册用户
等级:上尉
经验:753
发帖:66
精华:0
注册:2013-11-5
状态:离线
发送短消息息给lijia.peng 加好友    发送短消息息给lijia.peng 发消息
发表于: IP:您无权察看 2013-11-12 11:27:58 | [全部帖] [楼主帖] 楼主

__name__:


在使用自身的时候,就是main,比如你执行:

python test.py


此时在test.py里面的name就是main
如果你在test2中import test,那么name就是文件名http://www.cnblogs.com/herbert/archive/2011/09/27/2193482.html

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

if __name__ == '__main__':这段代码的主要作用主要是让该python文件既可以独立运行,也可以当做模块导入到其他文件。当导入到其他的脚本文件的时候,该main代码里面的就不执行了。参考:http://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函数了。




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论