改寫很簡單,就是再定義一次,方法的定義與函數 (function) 類似,兩者同樣使用關鍵字 (keyword) def ,如下例
class Demo:
def __init__(self):
self.i = 9527
def hello(self):
print("hello", self.i)
a = Demo(9527)
a.hello()
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:cla04.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

第 2 行到第 3 行,這裡是 __init__() 定義的地方
def __init__(self):
self.i = 9527凡是實體的方法都需要一個特別的參數 -- self , self 是個預設的保留字 (reserved word) ,所指的是實體本身自己,在 __init__() 所定義的實體屬性 (attribute) 都需要額外加上 self ,如第 3 行的 self.i 。
這裡, self.i 直接指派初值 9527 。
底下其它定義的實體方法可直接使用實體屬性,只需要寫 self.i 即可,例如第 5 行到第 6 行的 hello() 方法
def hello(self):
print("hello", self.i)__init__() 可以設定參數 (parameter) ,這樣使用建構子時便需提供參數值,例如
class Demo:
def __init__(self, i):
self.i = i
def hello(self):
print("hello", self.i)
a = Demo(1122)
a.hello()
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:cla05.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

| 中英文術語對照 | |
|---|---|
| 建構子 | constructor |
| 實體 | instance |
| 方法 | method |
| 改寫 | override |
| 函數 | function |
| 關鍵字 | keyword |
| 保留字 | reserved word |
| 屬性 | attribute |
| 參數 | parameter |
參考資料
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
2 則留言:
#cal05.py 修正如下
class Demo:
def __init__(self,i):
self.i=i
def hello(self,i):
print ('hello ', self.i)
a=Demo(123)
a.hello(123)
同樣 cal04.py 修正如下:
class Demo:
def __init__(self):
self.i = 9527
def hello(self):
print("hello", self.i)
a = Demo()
a.hello()
Hi, 文章都寫得很簡潔,很讚。不遇,self 不是保留字喔,那只是一個慣例,也可改成任何名字。
張貼留言