的确,什么是 Pythonic 呢?经常看到大家说这个是 Pythonic 而那个又不是,但如何定义,如何区分呢?这篇Blog给出了作者的一个解释。看这里

其中有几句话是这样说的:

To be Pythonic is to use the Python constructs and datastructures with clean, readable idioms. It is Pythonic is to exploit dynamic typing for instance, and it’s definitely not Pythonic to introduce static-type style verbosity into the picture where not needed. To be Pythonic is to avoid surprising experienced Python programmers with unfamiliar ways to accomplish a task.\

基本意思就是说如果想 Pythonic 就应该使用 Python 的构造和数据结构,并且要干净、符合可读性的习惯。例如使用动态类型是 Pythonic 的,而使用静态类型明显不是 Pythonic 的。想 Pythonic 就应该避免为了完成一件工作使用让有经验的 Python 程序员吃惊的不熟悉的方式。

就我个人对 Pythonic 的理解来说,简单、清晰,不要过分强调技巧,尽量使用 Python 已经提供的功能以及符合Python的思维方式。

其中最后还有一句话:

A less powerful framework that is easy to pick up for a Python programmer may be considered more Pythonic than a far more powerful system that takes more of a time investment to learn.

也就是说:一个功能不是很强但容易上手的框架比起功能强大但要花大量时间学习的框架来说更 Pythonic 。因为Python的哲学就是简单,美!

如果想了解 Python 的哲学或 Python 之禅(The Zen of Python),可以执行:

import this

它的内容真需要仔细研究:

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!

– by Tim Peters

上面的中文翻译已经在 啄木鸟社区有一个翻译了,不过说实在的真没仔细读过,现在读一读真是很有体会,不过我还是在各别用词上进行了修改,让我自已感觉更好吧。

优美胜过丑陋
明确胜过含蓄
简单胜过复杂
复杂胜过难懂
扁平胜过嵌套
稀疏胜过密集
易读亦有价
尽管实用会击败纯洁
特例也不能特殊到打破规则
除非明确地使其沉默
错误永远不应默默地溜掉
面对着不确定,要拒绝猜测的诱惑
应该有一个–宁肯只有一个–明显的实现方法
也许这个方法开始不是很明显,除非你是荷兰人
尽管不做通常好过立刻做
但现在做也要胜过不去做
如果实现很难解释,那它就是一个坏想法
如果实现容易解释,那它可能就是一个好想法
名字空间是一个响亮的出色想法–就让我们多用用它们

– Tim Peters


2条评论

  1. 能够把pythonic搞成诗歌的样子解释,酷!

  2. 生活也可以这样简单优雅~

发表评论

评论也有版权!