Bruce Eckel的一篇日志建議把self從方法的參數(shù)列表中移除,并把它作為一個(gè)關(guān)鍵字使用。
http://www.artima.com/weblogs/viewpost.jsp?thread=239003
Guido的這篇日志說(shuō)明了self作為參數(shù)是必不可少的。
http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html
第一個(gè)原因是保證foo.meth(arg)和C.meth(foo, arg)這兩種方法調(diào)用的等價(jià)(foo是C的一個(gè)實(shí)例),關(guān)于后者可以參見(jiàn)Python Reference Manual 3.4.2.3。這個(gè)原因理論上的意義比較大。
第二個(gè)原因在于通過(guò)self參數(shù)我們可以動(dòng)態(tài)修改一個(gè)類的行為:
#
?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就新增了一個(gè)meth方法,并且所有C的實(shí)例都可以通過(guò)c.meth(newval)調(diào)用這個(gè)方法。
前面兩個(gè)原因或許都可以通過(guò)一些workaround使得不使用self參數(shù)時(shí)實(shí)現(xiàn)同樣的效果,但是在存在decorator的代碼中Bruce的方法存在致命的缺陷。(關(guān)于decorator的介紹可以參見(jiàn)http://www.python.org/dev/peps/pep-0318/)
根據(jù)修飾對(duì)象,decorator分兩種,類方法和靜態(tài)方法。兩者在語(yǔ)法上沒(méi)有什么區(qū)別,但前者需要self參數(shù),后者不需要。而Python在實(shí)
現(xiàn)上也沒(méi)有對(duì)這兩種方法加以區(qū)分。Bruce日志評(píng)論中有一些試圖解決decorator問(wèn)題的方法,但這些方法都需要修改大量底層的實(shí)現(xiàn)。
最后提到了另一種語(yǔ)法糖實(shí)現(xiàn),新增一個(gè)名為classmethod的decorator,為每個(gè)方法加上一個(gè)self參數(shù),當(dāng)然這種實(shí)現(xiàn)也沒(méi)必要把self作為關(guān)鍵字使用了。不過(guò)我覺(jué)得這么做還不如每次寫(xiě)類方法時(shí)手工加個(gè)self =_=