Python小姿势 - Python之禅

2023-04-28 16:16:31 浏览数 (1)

Python之禅

Python之禅(The Zen of Python)是Python之父Guido van Rossum所著的一篇文章,总结了Python语言的哲学。

文章开头写道:

代码语言:javascript复制
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!

下面我们逐行分析一下这些名言。

Beautiful is better than ugly.

“美丽胜于丑陋”。这句话的意思是说,我们应该尽量写出美丽的代码,而不是丑陋的代码。

这也是PEP20中所说的“There should be one-- and preferably only one --obvious way to do it”的另一种表达。

Explicit is better than implicit.

“明了胜于晦涩”。这句话的意思是说,我们应该尽量写出明了的代码,而不是晦涩难懂的代码。

这句话的含义与“Readability counts.”是一致的。

Simple is better than complex.

“简单胜于复杂”。这句话的意思是说,我们应该尽量写出简单的代码,而不是复杂的代码。

这句话的含义与“There should be one-- and preferably only one --obvious way to do it”是一致的。

Complex is better than complicated.

“复杂胜于繁琐”。这句话的意思是说,我们应该尽量写出复杂的代码,而不是繁琐的代码。

这句话的含义与“There should be one-- and preferably only one --obvious way to do it”是一致的。

Flat is better than nested.

“扁平胜于嵌套”。这句话的意思是说,我们应该尽量写出扁平的代码,而不是嵌套的代码。

0 人点赞