博主在刚开始学习python时候,经常看到python脚本的最后部分会去执行 if __name__ == '__main__'这个判断,但是添加这个判断到底有什么作用博主并不知情。
在python当中是有模块的概念的,每个模块都有一个自己的名称,可以通过模块内置的__name__属性来得到模块的名称。而模块的名称又取决于python模块的使用的方式,因为模块既可以自己直接执行,也可以导入到别的模块当中使用。
我这里用代码举个例子:
#!/usr/bin/python # Filename: pylocal.py def showName(): print("The name of module is", __name__) if __name__ == '__main__': print('pylocal.py is being run by itself') showName() else: print('pylocal.py is being imported into another module') showName() #!/usr/bin/python # Filename: pyother.py from pylocal import showName if __name__ == '__main__': print('pyother.py is being run by itself') showName() else: print('pyother.py is being imported into another module') showName()这里我在pylocal.py这个模块当中定义了一个名为showName的函数,同时在两个模块当中分别加入了if __name__ == '__main__'这个判断,与此同时pyother.py模块中对pylocal.py做了一次导入操作。
当运行pylocal.py模块的时候,其运行结果如下:
pylocal.py is being run by itself The name of module is __main__当运行pyother.py模块的时候,其运行结果如下:
pylocal.py is being imported into another module The name of module is pylocal pyother.py is being run by itself The name of module is pylocal我们可以看到如下情况:
当pylocal.py模块直接运行时,这个模块的__name__值就是'__main__'。当pylocal.py模块被pyother.py模块调用的时候,那么这个模块(也就是pylocal.py模块)的__name__的值就是该模块的文件名(不带文件路径和文件的扩展名),即pylocal同时,我们也看到了模块在被其他模块导入的过程当中也执行了一次。