Re: [問題] __name__的使用時機?

看板Python作者 (godfat 真常)時間16年前 (2009/06/24 15:27), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串3/3 (看更多)
※ 引述《RUReady2 (Are you ready,too?)》之銘言: : 推 luke93:請參考 http://tinyurl.com/ltfmql 06/24 13:54 : l大給的網頁講得有點模糊 : Knowing this, you can design a test suite for your module within the module : itself by putting it in this if statement. : 這句話讓我不太懂放了這個statement對於我的模組做出什麼樣的testing 不是這件事可以讓你做什麼 test, 只是讓你方便執行 test. : 推 godfat:就是說,單獨執行時你的程式名稱是 __main__, 反之是原名 06/24 14 : → godfat:你可以寫成單獨執行時跑 test suite, 反之是一般模組 06/24 14 : → RUReady2:g大講的第二句看不懂 可以請g大舉個例嗎? 06/24 14 範例: # lib.py class Lib: def greet(): print('hi') def main(): print('my name is: ' + __name__) if __name__ == '__main__': main() main() 執行: python3.0 lib.py ==> my name is: __main__ my name is: __main__ 原因: 因為單獨執行,因此 __name__ 是 '__main__', 執行 main() 接著後面又執行了一次 main(), 共印出兩次。 # my.py import lib lib.Lib.greet() 執行: python3.0 my.py ==> my name is: lib hi 原因: import 進去時,__name__ 是 lib, 沒有觸動 if, 只執行最下面的 main() 一次 呼叫 lib.Lib.greet() 叫上面定義的 greet, 印出 hi. 跟測試有何關? 拿掉 lib.py 最底下的 main(), 把測試程式寫在 main() 裡,這樣一來, 當你執行: python lib.py 這樣就會執行 main() 並做你的測試。反之,被 import 則不會觸發 main(), 因此就不會執行測試程式,只是單純當成 module 被 import. 測試還是要你自己寫,這只是告訴你這樣執行比較方便而已。 不然可能會變成類似: python test.py lib.py 比較囉嗦一點。 或是當成獨立程式,例如: python ls.py 這樣當 ls 用,而你也可以在其他 python script 裡 import ls, 單純當成 ls 的 library 來使用。如: ls.list_files('*.py') -- By Gamers, For Gamers - from the past Interplay -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.128.121.85

06/24 17:24, , 1F
謝謝解答 除了獨立程式外小弟大概都了解了
06/24 17:24, 1F
文章代碼(AID): #1AGTLJoT (Python)
文章代碼(AID): #1AGTLJoT (Python)