python 中 if__name__==‘main’
python 中__name__ = '__main__' 的作用,到底干嘛的?
其实是让你写的脚本模块可以导入到其他的模快中用,另外该模块自己也可以执行。
首先创建一个文件夹,在文件夹中创建test1,test2
两个模块:
#test1.py
def test():
print("we are in %s"%__name__)
if __name__=='__main__':
test()
再写一个模块,导入test1
模块
test2.py
from test import test1
test1.test()
我们执行以下test1.py
模块,结果打印出”we are in __main__“
,说明我们的if语句中的内容被执行了,调用了test():
但是如果我们从另外一个模块导入该模块,并调用一次test()函数会是怎样的结果呢?
其执行的结果是:we are in module
但是没有显示”we are in __main
“,也就是说模块name__ = '__main__'
下面的函数没有执行。
这样既可以让“模块”文件运行,也可以被其他模块引入,而且不会执行函数2次。这才是关键。