Posted on 2008-11-15 19:58
ZelluX 閱讀(2536)
評論(2) 編輯 收藏 所屬分類:
OOP
Bruce Eckel的一篇日志建議把self從方法的參數(shù)列表中移除,并把它作為一個關(guān)鍵字使用。
http://www.artima.com/weblogs/viewpost.jsp?thread=239003
Guido的這篇日志說明了self作為參數(shù)是必不可少的。
http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html
第一個原因是保證foo.meth(arg)和C.meth(foo, arg)這兩種方法調(diào)用的等價(foo是C的一個實例),關(guān)于后者可以參見Python Reference Manual 3.4.2.3。這個原因理論上的意義比較大。
第二個原因在于通過self參數(shù)我們可以動態(tài)修改一個類的行為:
#
?Define?an?empty?class:
class
?C:
pass
?
#
?Define?a?global?function:
def
?meth(myself,?arg):
myself.val?
=
?arg
return
?myself.val
?
#
?Poke?the?method?into?the?class:
C.meth?
=
?meth
這樣類C就新增了一個meth方法,并且所有C的實例都可以通過c.meth(newval)調(diào)用這個方法。
前面兩個原因或許都可以通過一些workaround使得不使用self參數(shù)時實現(xiàn)同樣的效果,但是在存在decorator的代碼中Bruce的方法存在致命的缺陷。(關(guān)于decorator的介紹可以參見http://www.python.org/dev/peps/pep-0318/)
根據(jù)修飾對象,decorator分兩種,類方法和靜態(tài)方法。兩者在語法上沒有什么區(qū)別,但前者需要self參數(shù),后者不需要。而Python在實
現(xiàn)上也沒有對這兩種方法加以區(qū)分。Bruce日志評論中有一些試圖解決decorator問題的方法,但這些方法都需要修改大量底層的實現(xiàn)。
最后提到了另一種語法糖實現(xiàn),新增一個名為classmethod的decorator,為每個方法加上一個self參數(shù),當(dāng)然這種實現(xiàn)也沒必要把self作為關(guān)鍵字使用了。不過我覺得這么做還不如每次寫類方法時手工加個self =_=