深入理解python中if?__name__?==?‘__main__‘
1. 一個(gè)簡(jiǎn)單的例子
先來看一份代碼:
# test.py def addFunc(a, b): return a + b print('the result of test is: 1 + 1 = ', addFunc(1, 1))
# mode.py import test print('The result of test modula is :', test.addFunc(12, 23))
執(zhí)行 mode.py 輸出如下:
the result of test is: 1 + 1 = 2
The result of test modula is : 35
這里輸出的語句中,同時(shí)包含了 test.py 和 mode.py 中的內(nèi)容。那么問題來了,很多時(shí)候調(diào)用者并不需要輸出 test.py 里面的內(nèi)容,這個(gè)時(shí)候應(yīng)該怎么處理呢?添加另外一個(gè)不輸出的版本 test_no_print.py ?
python 中提供了 __name__ 這個(gè)系統(tǒng)變量來解決這個(gè)問題,先看修改后的代碼:
# test.py def addFunc(a, b): return a + b if __name__ == '__main__': print('the result of test is: 1 + 1 = ', addFunc(1, 1))
單獨(dú)執(zhí)行 test.py 結(jié)果如下:
the result of test is: 1 + 1 = 2
沒有問題,這是我們想要的結(jié)果。
執(zhí)行 mode.py:
The result of test modula is : 35
這恰恰也是我們想要的結(jié)果。
那么問題來了,__name__ 里面究竟是個(gè)什么神奇的值?
2. __name__ 的值
修改 test.py 如下使其輸出 __name__ 的值:
# test.py def addFunc(a, b): return a + b if __name__ == '__main__': print('the result of test is: 1 + 1 = ', addFunc(1, 1)) print("The value of '__name__' is ", __name__)
分別執(zhí)行 test.py 和 mode.py 結(jié)果如下:
the result of test is: 1 + 1 = 2
The value of '__name__' is __main__
The value of '__name__' is test
The result of test modula is : 35
可以看到,單獨(dú)執(zhí)行 test.py 時(shí),__name__ 的值是 ‘__main__’,而作為模塊被 import 到其他文件中調(diào)用時(shí),__name__ 的值則是模塊的名字。
我們知道,有兩種方法可以使用 python 文件來執(zhí)行它實(shí)現(xiàn)的功能,一個(gè)是直接運(yùn)行,一個(gè)是被其他文件導(dǎo)入后調(diào)用。當(dāng)它被直接運(yùn)行時(shí),當(dāng)前文件就是程序的主入口,這相當(dāng)于 C 或者 Java 中的 main 函數(shù)。當(dāng)它被其他文件導(dǎo)入調(diào)用時(shí),程序的入口自然在其他文件中。
__name__ 是 python 的內(nèi)置屬性,這個(gè)系統(tǒng)全局變量用來表示當(dāng)前模塊的名字。而 __main__ 就是一個(gè)代表程序入口的字符串。 因此 if __name__ == ‘__main__’ 其實(shí)就是判斷程序的入口是不是當(dāng)前的文件!
到此這篇關(guān)于深入理解python中if __name__ == ‘__main__‘的文章就介紹到這了,更多相關(guān)python if __name__ == ‘__main__‘內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實(shí)現(xiàn)將json格式數(shù)據(jù)存儲(chǔ)到Mysql數(shù)據(jù)庫
這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)將json格式數(shù)據(jù)存儲(chǔ)到Mysql數(shù)據(jù)庫,文中的示例代碼簡(jiǎn)潔易懂,有需要的小伙伴可以參考下2025-03-03一步一步教你用Python?pyglet仿制鴻蒙系統(tǒng)里的時(shí)鐘
pyglet是一個(gè)面向Python的跨平臺(tái)窗口、多媒體庫,它可以用于創(chuàng)建游戲和多媒體應(yīng)用程序,下面這篇文章主要給大家介紹了關(guān)于如何一步一步教你用Python?pyglet仿制鴻蒙系統(tǒng)里的時(shí)鐘,需要的朋友可以參考下2024-03-03python中from module import * 的一個(gè)坑
from module import *把module中的成員全部導(dǎo)到了當(dāng)前的global namespace,訪問起來就比較方便了。當(dāng)然,python style一般不建議這么做,因?yàn)榭赡芤餹ame conflict。2014-07-0790行Python代碼開發(fā)個(gè)人云盤應(yīng)用
這篇文章主要介紹了90行Python代碼開發(fā)個(gè)人云盤應(yīng)用,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2021-04-04