python - __name__= __main__怎么解释 怎么用 另外两个py文件之间的互动关联
巴扎黑
巴扎黑 2017-04-18 10:25:24
0
4
572

name = '__main__' 的作用
有句话经典的概括了这段代码的意义:

“Make a script both importable and executable”

意思就是说让你写的脚本模块既可以导入到别的模块中用,另外该模块自己也可执行。
def foo():
    print('in foo')
print(__name__)
foo()
if __name__=='__main__':
    foo()
返回结果
main   意思是__name__=__main,所以if语句判断True。

ob05.py
def func():
    print("func() in ob05.py")
print("top-level in ob05.py")

if name == "__main__":
    print("ob05.py is being run directly")
else:
    print("ob05.py is being imported into another module")
结果:
top-level in ob05.py
ob05.py is being run directly

ob06.py
import ob05
print("top-level in ob06.py")
ob05.func()
if name == "__main__":
    print("ob06.py is being run directly")
else:
    print("ob06.py is being imported into another module")
结果:
top-level in ob05.py
ob05.py is being imported into another module
top-level in ob06.py
func() in ob05.py
ob06.py is being run directly

Thus, when module one gets loaded, its name equals "one" instead of __main__.
意思是ob05模块被导入的话,ob05模块中的__name__=__main__
解释错或不对不完善 麻烦完善下 
那import是干嘛用呢,就引入了一个func()?name == "__main__" 是什么意思 起什么作用

巴扎黑
巴扎黑

reply all(4)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!