一直困扰我的一个问题就是
if __name__ == '__main__':
这行代码到底是用来干嘛的。
今天做一个作业才看到:
When a module is imported, all code in the module is immediately executed. Python programs often use the built-in special name __name__ to determine if the file was executed as a script by the programmer, or if the file was imported by another module. If the value of __name__ is the string ‘__main__’, then the file was executed as a script.
原来是用来确认这个python文件是被当作脚本执行还是被import到另一个文件中。如果直接运行该脚本,则if分支中的代码被执行;如果该脚本是被别的脚本import了,那么__name__的值就不是__main__,所以后面的代码就不会被执行。