定義類別使用關鍵字 (keyword) class ,形式如下
class Class_Name:
pass內建函數 help() 會顯示物件(包括類別)的資訊, dir() 則會把物件(包括類別)的所有屬性與方法以串列 (list) 列出
class Demo:
pass
help(Demo)
print(dir(Demo))
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:cla01.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

按 q 可以離開 help() 介面

第一張圖的 help() 介面好像看不出什麼,第二張圖告訴我們自行定義的類別,已經有許多預設的屬性及方法,這些屬性與方法的名稱前後都用連續兩個底線符號圍起來。
我們將 Demo 定義一個 i 屬性與一個 hello() 方法,然後再來看看 help() 資訊
class Demo:
i = 9527
def hello(self):
print("hello")
help(Demo)
print(dir(Demo))
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:cla02.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

多了兩項資訊,上面是 hello() 方法,下面是 i 屬性。
離開 help() 介面,我們看到 dir() 所具有的資訊

串列的最後多了 'hello' 與 'i' ,也就是我們剛剛在 Demo 加入的屬性與方法。
我們接下來看看怎麼建立物件
class Demo:
i = 9527
def hello(self):
print("hello")
d = Demo()
print(type(Demo))
print(type(d))
print()
print(d.i)
d.hello()
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:cla03.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

Demo 是類別名稱,第 7 行
d = Demo()
Demo() 就是 Demo 類別建立物件的建構子 (constructor) ,這裡利用指派運算子將建構子所建立的實體物件 (instance) 給變數 d ,於是 d 就具有 Demo 型態的物件。
Demo 類別也就是 Demo 型態,因此第 8 行印出的結果會是 'type' ,第 9 行印出變數 d 的型態為 '__main__.Demo' , '__main__' 則表示區域。
第 11 行
print(d.i)
物件利用小數點可以存取屬性或呼叫方法,這裡用小數點取得屬性 i 之值。
第 12 行
d.hello()
同樣的,變數 d 利用小數點呼叫 hello() 方法。
| 中英文術語對照 | |
|---|---|
| 類別 | class |
| 物件 | object |
| 屬性 | attribute |
| 方法 | method |
| 變數 | variable |
| 函數 | function |
| 關鍵字 | keyword |
| 串列 | list |
| 建構子 | constructor |
| 實體物件 | instance |
參考資料
http://docs.python.org/py3k/tutorial/classes.html
http://docs.python.org/py3k/reference/compound_stmts.html
http://docs.python.org/py3k/tutorial/classes.html
http://docs.python.org/py3k/reference/compound_stmts.html
沒有留言:
張貼留言