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