首页 / 知识库 / 0基础入门-阅读资料 / 0基础-python入门到精通

附录 C Python 之禅(The Zen of Python)解读

在 Python 解释器中输入 import this 即可看到这首”诗”,它凝练了 Python 的设计哲学。

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!

逐条解读

1. Beautiful is better than ugly. — 优美胜于丑陋

# 丑陋
if (x>0 and x<100 and y>0 and y<100): pass

# 优美
if 0 < x < 100 and 0 < y < 100: pass

代码不仅给机器执行,更给人阅读。追求优雅的表达。

2. Explicit is better than implicit. — 明确胜于隐晦

# 隐晦
from os import *   # 导入了什么?不知道

# 明确
from os import path, getcwd  # 一目了然

不要依赖隐含的行为,让代码的意图清楚可见。

3. Simple is better than complex. — 简单胜于复杂

# 复杂
result = (lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v))))(
    lambda f: lambda n: 1 if n <= 1 else n * f(n - 1)
)(5)

# 简单
def factorial(n):
    return 1 if n <= 1 else n * factorial(n - 1)

能用简单方案解决的问题,不要引入不必要的复杂性。

4. Complex is better than complicated. — 复杂胜于凌乱

当问题本身就是复杂的,有条理的复杂方案优于混乱无序的方案。数据库 ORM 是复杂的,但比到处写 SQL 字符串要好。

5. Flat is better than nested. — 扁平胜于嵌套

# 过度嵌套
if user:
    if user.is_active:
        if user.has_permission:
            do_something()

# 扁平(提前返回)
if not user:
    return
if not user.is_active:
    return
if not user.has_permission:
    return
do_something()

6. Sparse is better than dense. — 稀疏胜于紧凑

# 紧凑(难读)
result={k:v for d in[a,b,c]for k,v in d.items()if v>0}

# 稀疏(清晰)
result = {
    k: v
    for d in [a, b, c]
    for k, v in d.items()
    if v > 0
}

不要把所有逻辑挤在一行,适当的空白和换行让代码呼吸。

7. Readability counts. — 可读性很重要

这也许是最重要的一条。代码被读的次数远多于被写的次数。

# 聪明但难读
x = x or default_val

# 清晰
if x is None:
    x = default_val

8-9. Special cases aren’t special enough to break the rules. Although practicality beats purity.

规则很重要,但也不能教条。99% 的情况遵循规则,1% 的情况允许务实的例外。

10-11. Errors should never pass silently. Unless explicitly silenced.

# 坏 — 吞掉所有异常
try:
    do_something()
except:
    pass

# 好 — 明确处理特定异常
try:
    do_something()
except SpecificError:
    logger.warning("已知问题,安全忽略")

12. In the face of ambiguity, refuse the temptation to guess.

# Python 拒绝猜测
"3" + 5   # TypeError,不会猜你想要 "35" 还是 8

# JavaScript 会猜
# "3" + 5 → "35" (猜你想拼接)

13-14. There should be one obvious way to do it.

Python 追求每个问题有一个显而易见的解决方案。

# 字符串格式化的"唯一推荐方式"
name = "Alice"
f"Hello, {name}!"   # f-string — 这就是那个唯一推荐的方式

15-16. Now is better than never. Although never is often better than right now.

行动比空想好,但不要急于实现一个半成品。先想清楚,再动手。

17-18. 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.

如果你无法向同事解释你的代码在做什么,那代码可能需要重写。

19. Namespaces are one honking great idea — let’s do more of those!

# 命名空间避免了名称冲突
import json          # json.dumps
import pickle        # pickle.dumps
# 两个 dumps 互不干扰

# 模块、类、函数都创建命名空间

总结

Python 之禅不是教条,而是指导原则。当你犹豫该如何写代码时,想想这些原则:

  • 可读性永远是第一优先级
  • 简单明确优于复杂隐晦
  • 务实优于纯粹
  • 错误要显式处理
  • 遇到歧义要拒绝猜测