Python中if __name__ == '__main__' 的作用和原理

参考网址:http://mp.weixin.qq.com/s/kxxhOQ7KB_VMwWeUENX7OQ

t1.py:

print('Loving Python')

def main():
    print('Loving Python')
#print (__name__)
if __name__ == '__main__': main() print('Loving Python more')

result:

Loving Python
#__main__ Loving Python Loving Python more

t2.py

import testindex.t1

result:

Loving Python
#testindex.t1

从上面我们可以看出,t2.py中只是执行了t1中的第一行,if __name__ == '__main__': 后面的数据都未执行

t1.py:

print('Loving Python')

def main():
    print('Loving Python')
print (__name__) if __name__ == '__main__': main() print('Loving Python more')

result:

Loving Python
__main__ Loving Python Loving Python more

t2.py

import testindex.t1

result:

Loving Python
testindex.t1

然后我们在t1.py中添加print (__name__),在t1.py中结果为__main__,在t2.py中结果为testindex.t1

再仔细想想,其运行原理也就是:

由于每个python模块(python文件)都包含内置的变量__name__,当运行模块被执行的时候,__name__等于文件名(包含了后缀.py)。如果import到其他模块中,则__name__等于模块名称(不包含后缀.py)。而“__main__”等于当前执行文件的名称(包含了后缀.py)。所以当模块被直接执行时,__name__ == '__main__'结果为真;而当模块被import到其他模块中时,__name__ == '__main__'结果为假,就是不调用对应的方法。

简而言之就是:__name__ 是当前模块名,当模块被直接运行时模块名为 __main__ 。当模块被直接运行时,代码将被运行,当模块是被导入时,代码不被运行。

原文地址:https://www.cnblogs.com/fireporsche/p/8529458.html