您的位置:首页 > 编程语言 > Python开发

python 开始! Python 关于 name main的使用

2014-11-25 16:39 211 查看
python开始restapi开始

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

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

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

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

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

?
参考:

http://pyfaq.infogami.com/tutor-what-is-if-name-main-for


The
if__name__=="__main__":...
trickexistsinPythonsothatourPythonfilescanactaseitherreusablemodules,orasstandaloneprograms.Asatoyexample,let'ssaythatwehavetwofiles:

mumak:~dyoo$catmymath.py


mymath.py文件


?
mumak:~dyoo$catmygame.py


mygame.py文件

?
Inthisexample,we'vewrittenmymath.pytobebothusedasautilitymodule,aswellasastandaloneprogram.Wecanrunmymathstandalonebydoingthis:

mumak:~dyoo$pythonmymath.py
test:square(42)==1764

Butwecanalsousemymath.pyasamodule;let'sseewhathappenswhenwerunmygame.py:

mumak:~dyoo$pythonmygame.py
thisismygame.
289

Noticethatherewedon'tseethe'test'linethatmymath.pyhadnearthebottomofitscode.That'sbecause,inthiscontext,mymathisnotthemainprogram.That'swhatthe
if__name__=="__main__":...
trickisusedfor.

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

伪python爱好者,正宗测试实践者。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: