Python 關於 name main的使用

來源:互聯網
上載者:User

看過很多python的code都有這段代碼:

if __name__ == '__main__':
這段代碼的主要作用主要是讓該python檔案既可以獨立運行,也可以當做模組匯入到其他檔案。當匯入到其他的指令檔的時候,該main代碼裡面的就不執行了。
參考:
http://pyfaq.infogami.com/tutor-what-is-if-name-main-for
 

The if __name__ == "__main__": ... trick exists in Python so that our Python files can act as either reusable modules, or as standalone programs. As a toy example, let's say that we have two files:

mumak:~ dyoo$ cat mymath.pydef square(x):    return x * xif __name__ == '__main__':    print "test: square(42) ==", square(42)mumak:~ dyoo$ cat mygame.pyimport mymathprint "this is mygame."print mymath.square(17)

In this example, we've written mymath.py to be both used as a utility module, as well as a standalone program. We can run mymath standalone by doing this:

mumak:~ dyoo$ python mymath.pytest: square(42) == 1764

But we can also use mymath.py as a module; let's see what happens when we run mygame.py:

mumak:~ dyoo$ python mygame.pythis is mygame.289

Notice that here we don't see the 'test' line that mymath.py had near the bottom of its code. That's because, in this context, mymath is not the main program. That's what the if __name__ == "__main__": ... trick is used for.

 

在這個例子裡面mygame.py裡面調用square函數的時候,就不會執行mymath.py裡面的main函數了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.