python中使用if __name__ == '__main__':
引子
在python中,假設(shè)在一個(gè)test1.py的模塊中定義了一個(gè)foo函數(shù),然后調(diào)用函數(shù)foo進(jìn)行測試的時(shí)候會(huì)產(chǎn)生一個(gè)內(nèi)存空間。當(dāng)你把這個(gè)模塊導(dǎo)入到test2.py模塊中,接下來如果在test2.py模塊中執(zhí)行某一段代碼的時(shí),就會(huì)自動(dòng)執(zhí)行test1.py模塊中的foo函數(shù)。這樣會(huì)導(dǎo)致什么問題呢?會(huì)導(dǎo)致你原本只想測試當(dāng)前的代碼,又自動(dòng)執(zhí)行了另一個(gè)模塊中的函數(shù)。
那如何解決這個(gè)問題:
一 導(dǎo)入模塊自動(dòng)執(zhí)行問題
test1.py# 定義foo函數(shù) def foo():print('from foo...') foo() # from foo...?
test2.pyfrom test_1 import test1# 在test2.py模塊中打印test1.py模塊中的__name__屬性發(fā)生了變化 print(test1.__name__) # test_1.test1def bar():print('from bar...')bar() # 此時(shí)會(huì)在當(dāng)前文件中執(zhí)行bar函數(shù)會(huì)自動(dòng)執(zhí)行test1模塊中的foo函數(shù) ''' from foo... from bar... '''二 使用if __name__ == '__main__' 解決自動(dòng)執(zhí)行問題
? 因?yàn)樵趐ython中一切皆對(duì)象,其實(shí)模塊也是一個(gè)對(duì)象,那么每一個(gè)模塊中都包含著一個(gè)__name__屬性,而這個(gè)屬性會(huì)根據(jù)模塊所在的位置而發(fā)生變化。我們可以通過對(duì)__name__這個(gè)屬性進(jìn)行判斷。從而解決因?yàn)閷?dǎo)入其他模塊自動(dòng)執(zhí)行的問題。
1、test1.py模塊中打印__name__屬性。
test1.py # 定義foo函數(shù) def foo():print('from foo...')# 在當(dāng)前文件中的__name__屬性值 print(__name__) # __main__ foo() # from foo...2、在test2.py模塊中執(zhí)行bar函數(shù)
test2.pyfrom test_1 import test1# 在test2.py模塊中打印test1.py模塊中的__name__屬性發(fā)生了變化 print(test1.__name__) # test_1.test1def bar():print('from bar...')bar() # 此時(shí)會(huì)在當(dāng)前文件中執(zhí)行bar函數(shù)會(huì)自動(dòng)執(zhí)行test1模塊中的foo函數(shù) ''' from foo... from bar... '''?
3、在test1.py中添加if __name__ == '__main__'判斷
由上述可見,test1.py模塊中的__name__會(huì)根據(jù)執(zhí)行文件的位置發(fā)生變化,由此我們可以通過對(duì)__name__屬性進(jìn)行判斷調(diào)用者是否在當(dāng)前模塊調(diào)用函數(shù)進(jìn)行測試。如果不是當(dāng)前文件執(zhí)行,就不會(huì)執(zhí)行調(diào)用的函數(shù)。
test1.py # 定義foo函數(shù) def foo():print('from foo...')# 在當(dāng)前文件中的__name__屬性值 print(__name__) # __main__if __name__ == '__main__': # __name__: test_1.test1foo() test2.pyfrom test_1 import test1print(test1.__name__) # test_1.test1def bar():print('from bar...')bar() # from bar...這就是為何在python中要使用if __name__ == ‘__main__’進(jìn)行對(duì)函數(shù)功能的測試了!
?
轉(zhuǎn)載于:https://www.cnblogs.com/kermitjam/p/10693110.html
總結(jié)
以上是生活随笔為你收集整理的python中使用if __name__ == '__main__':的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【HNOI2019】部分题简要题解
- 下一篇: 简单了解Python网络爬虫