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__" 是什么意思 起什么作用
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…