為什么需要self
? 這兩天coding的時候想到一個問題媚值,Python中class為什么需要self作為內(nèi)部方法的第一個入?yún)ⅲ棵黠@的解釋是解決class內(nèi)符號作用域的問題藐握。類內(nèi)的變量和函數(shù)靴拱,全局變量和函數(shù)非常明確的區(qū)分開,理解起來也很清晰猾普。至于編譯器實現(xiàn)上袜炕,不應該有什么繞不過去的問題。
但self從coding角度看有點傻抬闷,不夠簡潔妇蛀,即便編輯器可以提供幫助自動補出還是有點傻。所以還需要進一步從 Python 的設計理念看看笤成。<zen of the Python> 中有一條可以用self做腳注
Explicit is better than implicit,
顯示/明確的 勝過 隱含的眷茁。self雖然傻炕泳,但傻得明確,避免一些隱含的錯誤上祈。
實際上 Python 不必像c++那么富有技巧性培遵,技巧性對于高手可以極有價值,但普遍而言未必是好事情登刺。換言之籽腕,越貼近業(yè)務的代碼技巧性應該越低;越抽象工具性代碼纸俭,可以充滿抽象和技巧皇耗。
再讀一遍 the zen of Python的原文:
The Zen of Python , by Tim Peter
Beautiful is better than ugly.
? ? 注: 明顯難看的東西,比如違反clean code的東西揍很。
Explicit is better than implicit.
? ? 注: self
Simple is better than complex.
Complex is better than complicated.
? ? 注: 這兩句很有意思郎楼,復雜性如果是本質(zhì)的,就用復合窒悔,組合的方式來實現(xiàn)呜袁,要能拆的開,合得上简珠,組合式編程阶界,樂高模樣。否則復雜性是無法管理的。
Flat is better than nested.
? ? 注: 扁平比嵌套的好膘融,能扁平當然別分級嵌套要好芙粱。但存在問題是扁平的模塊間關(guān)系不能太復雜,網(wǎng)狀的就別扁平了托启。
Sparse is better than dense.
? ? 注: 稀疏勝于質(zhì)密宅倒,應該指的是模塊或元素間的關(guān)系,稀疏是清晰的屯耸,質(zhì)密就是上文說的網(wǎng)狀結(jié)構(gòu)拐迁。其實就是高內(nèi)聚低耦合的另一個說法。
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never. Although never is often better than *right* now.
? 注: 這個說的很有道理疗绣,我讀來感覺痛入骨髓线召。雖說做比不做好,但瞎做還不如不做多矮。行成于思缓淹。思重于行。特別是做研發(fā)的塔逃,不想讯壶,不設計,直接動手湾盗》茫可怕的很。
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
注: 難以理解的格粪,講都講不明白的實現(xiàn)躏吊,肯定不是好主意。有點像在解釋 Beautiful is better than ugly.
Namespaces are one honking great idea -- let's do more of those!