关于python中的 if __name__=='__main__': 的作用

来源:互联网 发布:英国博士申请知乎 编辑:程序博客网 时间:2024/04/29 11:45


先一句话总结,这句话的作用就是让一个py文件直接运行和作为模块被引入时有所区别。

具体表现在直接运行时,本句语句之后的内容会被执行,而作为模块时不会。


首先我们先写一个模块:

# Test.pydef main():    print("we are in %s" % __name__)print("This is a test")if __name__ == '__main__':    main()    print("this is a test,too!") 

然后用另外一个py文件来引入这个模块:

import Test

然后分别执行这两个程序,模块直接运行结果是:

This is a testwe are in __main__this is a test,too!

作为模块被引入后运行结果是:

This is a test


阅读全文
0 0