python中關於if name == ‘main’
author@jason_ql(lql0716)
http://blog.csdn.net/lql0716
__name__
是當前模塊名,當模塊被直接運行時模塊名爲__main__
。這句話的意思就是,當模塊被直接運行時,以下代碼塊將被運行,當模塊是被導入時,代碼塊不被運行。示例
# file one.py
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
# file two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
如果你執行one.py文件
python one.py
會輸出:
top-level in one.py
one.py is being run directly
如果你執行two.py文件,
python two.py
會輸出:
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
參考:鏈接
延伸閱讀
- 機器學習、深度學習、計算機視覺、自然語言處理及應用案例——乾貨分享(持續更新……)
http://blog.csdn.net/lql0716/article/details/70479493 - python數組寫入txt
http://blog.csdn.net/lql0716/article/details/52614809 - python矩陣轉換爲一維數組
http://blog.csdn.net/lql0716/article/details/52595590 - 最全Pycharm教程(18)——Pycharm編輯器功能之代碼拼寫提示
http://blog.csdn.net/lql0716/article/details/52477492 - python matplotlib 畫圖
http://blog.csdn.net/lql0716/article/details/74617957 - python - sorted()排序
http://blog.csdn.net/lql0716/article/details/54136015 - Python判斷一個文件或文件夾是否存在,並創建
http://blog.csdn.net/lql0716/article/details/53408985 - python之os.path模塊
http://blog.csdn.net/lql0716/article/details/52918552 - python之numpy.power()數組元素求n次方
http://blog.csdn.net/lql0716/article/details/52910812 - Python數據處理手冊
http://blog.csdn.net/lql0716/article/details/52770506 - Python基本手冊
http://blog.csdn.net/lql0716/article/details/52769441 - python–多個變量的for循環
http://blog.csdn.net/lql0716/article/details/52769110 - python矩陣運算
http://blog.csdn.net/lql0716/article/details/52387888
- 機器學習、深度學習、計算機視覺、自然語言處理及應用案例——乾貨分享(持續更新……)