self 和 The Zen of Python 的理解
为什么需要self
这两天coding的时候想到一个问题,Python中class为什么需要self作为内部方法的第一个入参?明显的解释是解决class内符号作用域的问题。类内的变量和函数,全局变量和函数非常明确的区分开,理解起来也很清晰。至于编译器实现上,不应该有什么绕不过去的问题。
但self从coding角度看有点傻,不够简洁,即便编辑器可以提供帮助自动补出还是有点傻。所以还需要进一步从 Python 的设计理念看看。<zen of the Python> 中有一条可以用self做脚注
Explicit is better than implicit,
显示/明确的 胜过 隐含的。self虽然傻,但傻得明确,避免一些隐含的错误。
实际上 Python 不必像c++那么富有技巧性,技巧性对于高手可以极有价值,但普遍而言未必是好事情。换言之,越贴近业务的代码技巧性应该越低;越抽象工具性代码,可以充满抽象和技巧。
再读一遍 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.
注: 这两句很有意思,复杂性如果是本质的,就用复合,组合的方式来实现,要能拆的开,合得上,组合式编程,乐高模样。否则复杂性是无法管理的。
Flat is better than nested.
注: 扁平比嵌套的好,能扁平当然别分级嵌套要好。但存在问题是扁平的模块间关系不能太复杂,网状的就别扁平了。
Sparse is better than dense.
注: 稀疏胜于质密,应该指的是模块或元素间的关系,稀疏是清晰的,质密就是上文说的网状结构。其实就是高内聚低耦合的另一个说法。
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.
注: 这个说的很有道理,我读来感觉痛入骨髓。虽说做比不做好,但瞎做还不如不做。行成于思。思重于行。特别是做研发的,不想,不设计,直接动手。可怕的很。
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.
注: 难以理解的,讲都讲不明白的实现,肯定不是好主意。有点像在解释 Beautiful is better than ugly.
Namespaces are one honking great idea -- let's do more of those!