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

引子

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

  那如何解決這個問題:函數

一 導入模塊自動執行問題

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__這個屬性進行判斷。從而解決由於導入其餘模塊自動執行的問題。測試

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

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

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

foo()  # from foo...

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

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...
'''

 

三、在test1.py中添加if __name__ == '__main__'判斷對象

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

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__’進行對函數功能的測試了!內存

相關文章
相關標籤/搜索