Python中__name__屬性的妙用

來源:互聯網
上載者:User

標籤:module   __name__   就是   col   執行   font   屬性   bsp   code   

在Python中,每一個module檔案都有一個built-in屬性:__name__,這個__name__有如下特點:

1 如果這個module檔案是被別的檔案匯入的,那麼,該__name__屬性的值就是這個module檔案的名字;

2 如果這個module檔案是被當成程式來執行,那麼,該__name__屬性的值就是"__main__"

 

因此,在很多Python代碼中,__name__屬性被用來區分上述module檔案被使用的兩種方式。一種常用的做法是將module檔案自己的單測代碼,放到__name__屬性為"__main__"的情形中去。

比如,有test.py檔案:

def tester():    print("It‘s Christmas in Heaven...")if __name__ == ‘__main__‘:     tester() # 調用單測代碼

如果這個檔案是被其他檔案匯入的,那麼,tester函數不會執行:

>>>import test       # tester函數不會執行,除非顯示調用>>>test.tester()It‘s Chrismas in Heaven...

但是如果test.py被當成程式執行,那麼,tester函數會執行:

python test.py
It‘s Chrisma in Heaven...

 

Python中__name__屬性的妙用

聯繫我們

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