看板 PLT 關於我們 聯絡資訊
brianhsu:BTW,Python 另一個我覺得很謎的地方是為什麼要傳 self 01/08 00:24
brianhsu:給 instance method。XD 01/08 00:24
這是一段蠻長的故事(old-style class 與 new-style class 各有一段)。 簡單地講,早期的 Python 為了簡單,實際上是沒有分 instance/class/static method。(以下是主要是針對 Python 2.2 以前的 old-style class) class Coord: def __init__(self, lat=0.0, lon=0.0): self.lat, self.lon = lat, lon def info(self): return 'Coord(lat=%s, lob=%s)' % (self.lat, self.lob) 上面的 def statement 出現在 class statement 內本身並沒有任何特殊之處(與 在其他地方使用 def statement 相同)。第一個 formal parameter 取名作 self 也沒有任何特殊的作用(只有可讀性)。 整個 class statement 的結果約略地說是建立一個 "class" object 並將此 object bind 在此 class statement 所在的 context 內。這個 "class" object 內含的 dict 會有兩個 binding:"__init__", "info" 分別指涉到兩個 function object。 c = Coord(10, 20) print Coord.info(c) # legal print c.info() # legal 在語法上 c.info() 可以看成是 c.__class__.info(c)。 說起來這比較像是寫 C 程式時,定義了一堆處理特定 struct 的 function(每個 function 的第一個 formal parameter 明白指定為特定 struct address),差別 在於 Python 是把這個相關的 function 收集在 class namespace,並且提供一個 用法比較接近一般的 OOP 的語法。 * 如果舉 new-style class 則會更複雜。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.173.133.36
sbrhsieh:我講的東西是過度簡化過的。old-style class 實際上有分 01/08 01:52
sbrhsieh:function 與 method(method 又分 bound/unbound)。 01/08 01:53
godfat:不知道是 old-style 比較複雜,還是 new-style..? 01/08 16:28
godfat:換成 new-style 有什麼特殊原因嗎? 01/08 16:28
new-style 比較複雜一點(但概念本身不複雜)。 引進 new-style class 的目的是為了 meta-programming,在沒有 new-style class 以前要作 meta-programming 只能從 C 層面下手,new-style class 的機制則讓 programmer 可以直接在 Python 語言層面去設計 meta class。 ※ 編輯: sbrhsieh 來自: 218.173.133.36 (01/08 19:46)