python中使用if __name__ == '__main__':


引子

  在python中,假設在一個test1.py的模塊中定義了一個foo函數,然后調用函數foo進行測試的時候會產生一個內存空間。當你把這個模塊導入到test2.py模塊中,接下來如果在test2.py模塊中執行某一段代碼的時,就會自動執行test1.py模塊中的foo函數這樣會導致什么問題呢?會導致你原本只想測試當前的代碼,又自動執行了另一個模塊中的函數。

  那如何解決這個問題:

一 導入模塊自動執行問題

test1.py

# 定義foo函數
def foo():
    print('from foo...')

foo()  # from foo...

 

test2.py from test_1 import test1

# 在test2.py模塊中打印test1.py模塊中的__name__屬性發生了變化
print(test1.__name__)  # test_1.test1

def bar():
    print('from bar...')

bar()  

# 此時會在當前文件中執行bar函數會自動執行test1模塊中的foo函數
'''
from foo...
from bar...
'''

二 使用if __name__ == '__main__' 解決自動執行問題

   因為在python中一切皆對象,其實模塊也是一個對象,那么每一個模塊中都包含着一個__name__屬性,而這個屬性會根據模塊所在的位置而發生變化。我們可以通過對__name__這個屬性進行判斷。從而解決因為導入其他模塊自動執行的問題。

1、test1.py模塊中打印__name__屬性。

test1.py # 定義foo函數
def foo():
    print('from foo...')

# 在當前文件中的__name__屬性值
print(__name__)  # __main__

foo()  # from foo...

2、在test2.py模塊中執行bar函數

test2.py from test_1 import test1

# 在test2.py模塊中打印test1.py模塊中的__name__屬性發生了變化
print(test1.__name__)  # test_1.test1

def bar():
    print('from bar...')

bar()  

# 此時會在當前文件中執行bar函數會自動執行test1模塊中的foo函數
'''
from foo...
from bar...
'''

 

3、在test1.py中添加if __name__ == '__main__'判斷

  由上述可見,test1.py模塊中的__name__會根據執行文件的位置發生變化,由此我們可以通過對__name__屬性進行判斷調用者是否在當前模塊調用函數進行測試。如果不是當前文件執行,就不會執行調用的函數。

test1.py 

# 定義foo函數
def foo():
    print('from foo...')

# 在當前文件中的__name__屬性值
print(__name__)  # __main__

if __name__ == '__main__':  # __name__: test_1.test1
    foo()
test2.py

from test_1 import test1

print(test1.__name__)  # test_1.test1

def bar():
    print('from bar...')
    
bar()  # from bar...

  這就是為何在python中要使用if __name__ == ‘__main__’進行對函數功能的測試了!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM