Suppose such a a.py file
def fun1():
........
def fun2():
.........
if __name__=='__main__':
......# some statements executed
When you execute this a.py file, __name__
=
=
'__main__'为真,后面的语句可以执行
When you import a file in another file and use it as a module,__name__
=
=
'__main__'为假,后面的语句不执行了,只有前面定义的函数其作用.
如果没有这句话话,你在b.py中引用a的话,那些执行语句也会执行。假设你只想引用a中的函数,那你就得加这句话。
Therefore, this sentence is to allow you to treat a file as both executable and importable modules. In Python, when you refer to a module, it will execute all the statements. If you only want the function, just block it with that sentence and don't look down, just find the function.
Each module has a built-in attribute __name__, which is '__main__' when it is executing a program, and 'a' is the name of the module when it is an import module.