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

t1.py:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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__ 。当模块被直接运行时,代码将被运行,当模块是被导入时,代码不被运行。

posted @ 2022-10-07 20:43  I'm_江河湖海  阅读(0)  评论(0)    收藏  举报