python中的__name__

python中我们常将一些方法封装在一个模块里,然后在另一个文件里通过import导入模块进行调用。

新建test.py文件,代码如下

def A():

    print("hello")

再简历main.py文件,代码如下

import test

test.A()

此时用python main.py执行,打印 hello。

但如果A()实现的代码很长,我们想要在test.py文件里调用A()进行测试,则需要:

def A():

    print("hello")

A()//测试

用python test.py执行,打印 hello。

但此时如果测试代码没有删除,调用者用python main.py执行,则会打印 hello hello。
因为A()被执行了两次。

为解决这一问题,我们需要这样做,在test.py文件里:

def A():

    print("hello")


if __name__ == '__main__'://加上这句在执行
    A()

用python main.py执行,则会打印 hello,结果正常

分析

在test.py中,加入print(__name__),看看__name__的值

def A():

    print("hello")

print(__name__)

if __name__ == '__main__'://加上这句在执行
    A()

此时如果用python test.py,则会打印__main__ hello,此时__name的值为\main__

如果用python main.py执行,则打印test hello,此时__name__的值为test

结论

因此可以看出,在函数所在的文件内调用函数,__name__的值为__main__

但是如果通过导入模块调用函数,则函数所在文件的__name__值为函数所在文件的文件名

文章目录
|