天天看点

python中__name__和__main__的辨析

《A Byte of Python》中文4.08C版,第71页。

if __name__ == '__main__':
    print('This program is being running by itself')
else:
    print('I am being imported from another module')
           

当你直接运行这段代码的时候,结果是:

D:\python\python.exe E:/python/project/module_using_name.py
This program is being running by itself

Process finished with exit code 0
           

当你用import语句导入时:

import module_using_name
print(module_using_name.__name__)
           

结果是:

D:\python\python.exe E:/python/project/test.py
I am being imported from another module
module_using_name

Process finished with exit code 0
           

这个结果说明了:在单独运行时,模块的__name__属性值是__main__;

当被导入时,模块__name__属性值是模块名module_using_name。

我理解为了模块名在单独运行是无法被自身读取的,所以取值为__main__。

在书中的代码添加了一行:

if __name__ == '__main__':
    print('This program is being running by itself')
else:
    print('I am being imported from another module')

print(__name__)
           

结果为:

D:\python\python.exe E:/python/project/module_using_name.py
This program is being running by itself
__main__

Process finished with exit code 0