Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

__name__= __main__怎么解释 怎么用 另外两个py文件之间的互动关联

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__" 是什么意思 起什么作用


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

简单来说就是每一个Python代码文件里都可以写上一段

if __name__ == '__main__':
    doSomething()

这里的dosomething只会在你直接在终端执行这个文件的时候会被调用,而不会在作为包import到其他文件并执行那个文件时调用。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...