
簡單說,我們要在建立 Encrypt 物件的同時就製作好密碼表,就把原來 setCode() 的內容移到 __init__() 的地方就可以了
def __init__(self):
self.code = [chr(i) for i in range(97, 123)]
random.shuffle(self.code)
self.alph = [chr(i) for i in range(97, 123)]這裡我們多增加一個實體屬性 (instance attribute) self.alph ,這是按字母順序的英文小寫字母表,等會編碼、解碼的時候都需要用到這個表格。
本來的 setCode() 仍保留,改成如下
def setCode(self, data):
self.code = list(data)新版的 setCode() 讓我們可由 data 設定密碼表,這裡預期 data 為密碼表的字串 (string) ,藉由內建函數 (function) list() 可以將字串轉換為具有 26 個字元的串列 (list) ,也就是我們需要的密碼表。
另外,我們也增加一個 __str__() 方法,如下
def __str__(self):
return "code: " + "".join(self.code)__str__() 也是個定義類別的特殊方法,用來設定物件的字串形式,也就是直接印出物件時印出的字串。
我們將 encrypt.py 修改如下
import random
class Encrypt:
def __init__(self):
self.code = [chr(i) for i in range(97, 123)]
random.shuffle(self.code)
self.alph = [chr(i) for i in range(97, 123)]
def __str__(self):
return "code: " + "".join(self.code)
def setCode(self, data):
self.code = list(data)
def getCode(self):
return "".join(self.code)
def toEncode(self):
return "toEncode"
def toDecode(self):
return "toDecode"
if __name__ == '__main__':
e = Encrypt()
print()
print(e)
print(e.toEncode())
print(e.toDecode())
print()
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:encrypt.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2012 年 12 月 執行部份就簡單的改成印出物件囉,執行結果如下

接下來我們要繼續設置 toEncode() 與 toDecode() ,也就是編碼與解碼的功能。
| 中英文術語對照 | |
|---|---|
| 類別 | class |
| 方法 | method |
| 物件 | object |
| 物件導向程式語言 | object-oriented programming language |
| 建構子 | constructor |
| 實體屬性 | instance attribute |
| 字串 | string |
| 函數 | function |
| 串列 | list |
您可以繼續參考
軟體開發
相關目錄
回 Python 入門指南
回 Python 教材
回首頁
參考資料
http://docs.python.org/3.1/tutorial/classes.html
沒有留言:
張貼留言