理解Python中的if __name__=='__main__'__Python

來源:互聯網
上載者:User

Python中每個模組都有一個名稱,當一個模組被第一次輸入的時候,這個模組的主塊(__main__)將被運行。假如我們只想在程式本身被使用的時候運行主塊,而在它被別的模組輸入的時候不運行主塊,我們該怎麼做呢。這可以通過模組的__name__屬性完成:

看下面這個例子:

a.py:

#!/usr/bin/python# Filename: a.pyif __name__ == '__main__':    print 'This program is being run by itself'else:    print 'I am being imported from another module'

b.py:

#!/usr/bin/python# Filename: b.pyimport a

運行:

$ python2.7 a.pyThis program is being run by itself$ python2.7 b.pyI am being imported from another module


-------

總結: 每個Python模組都有它的__name__,如果__name__是'__main__',這說明這個模組被使用者單獨運行


參考:

1.http://stackoverflow.com/questions/419163/what-does-if-name-main-do

2.http://sebug.net/paper/python/ch08s04.html


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.