
我們先用 encrypttest.py 來 import 本來的 encrypt.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import encrypt e = encrypt.Encrypt() e.setCode() print () print (e.getCode()) print (e.toEncode()) print (e.toDecode()) print () # 《程式語言教學誌》的範例程式 # 檔名:encrypttest.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2012 年 12 月 |
執行結果如下

因為 encrypttest.py 的執行程式部份與 encrypt.py 相同,因為 import 會先執行 encrypt.py 沒有縮排的程式碼,因此執行結果就好像 encrypttest.py 執行了兩次。
所以我們需要替 encrypt.py 加入 if __name__ == '__main__': 的條件判斷,如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import random class Encrypt: def setCode( self ): self .code = [ chr (i) for i in range ( 97 , 123 )] random.shuffle( self .code) def getCode( self ): return "".join( self .code) def toEncode( self ): return "toEncode" def toDecode( self ): return "toDecode" if __name__ = = '__main__' : e = Encrypt() e.setCode() print () print (e.getCode()) print (e.toEncode()) print (e.toDecode()) print () # 《程式語言教學誌》的範例程式 # 檔名:encrypt.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2012 年 12 月 |
這樣重新執行 encrypttest.py ,就 ok 囉

這樣 encrypt.py 就正式成為我們自行設計的模組 (module) 了,往後在 GUI 的 Python 程式中也是只要 import 就可以囉!不過我們希望建立物件同時建立好密碼表,這就要設定 __init__ 方法了。
中英文術語對照 | |
---|---|
變數 | variable |
模組 | module |
您可以繼續參考
軟體開發
相關目錄
回 Python 入門指南
回 Python 教材
回首頁
參考資料
http://docs.python.org/3.1/tutorial/classes.html
沒有留言:
張貼留言