天天看點

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