上QQ阅读APP看书,第一时间看更新
1.5 Python文化
许多编程语言是文化运动的中心。它们有自己的社区、价值观、实践和哲学,Python也不例外。开发者通过Python Enhancement Proposals(以下缩写为PEP)这一系列文档对Python语言的开发进行管理。其中一个PEP(名为PEP 8)解释了如何格式化代码,我们在本书中也会遵循该指南。例如,我们在新的Python代码中使用4个空格进行缩进,这也是PEP推荐的方式。
这些PEP文档中的另外一个文档PEP 20,被称为“Python之禅”。它引用了20条描述Python指导原则的格言,其中只有19条被记录下来。方便的是,Python之禅也内置在Python解释器中,你可以通过输入以下命令从REPL中看到它:
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
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.
Namespaces are one honking great idea -- let's do more of those!
在本书中,我们将在禅之刻(moments of zen)中特别强调Python之禅中的至理名言,以理解它们是如何运用在我们所学的知识中的。正如我们刚刚介绍的Python的缩进语法,这是我们展示禅之刻的好时机。
有时候,你会感激Python的缩进语法,它让你的代码变得优雅,也可以让你轻松读懂他人的代码。