网络知识 娱乐 Python之禅 -- 致初学者

Python之禅 -- 致初学者

在这里插入图片描述

Python之禅

Python社区的理念 ————“Zen of Python"

想要获悉这一指导原则,只要在Python解释器中执行命令import this

>>> 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.
......
  • 让我们来揭开这些有关优秀代码的秘密

The Zen of Python, by Tim Peters

python之禅,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.

除非你是荷兰人,否则这种方式一开始可能并不明显(这里指的是Python之父Guido)

Now is better than never.

现在开始做比不做好,所以如果想学编程却还在犹豫,请开动吧!

Although never is often better than right now.

不做比盲目去做好,极限编程的关键原则[YAGNI 是You Ain’t Gonna Need It(你不会需要它)]。即不要不要做过度设计

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!

命名空间是一个非常棒的想法——让我们更多地使用命名空间!(避免多人开发导致变量名重名情况,人手设置一个)

进程已结束,退出代码0,你现在是否学会了优秀代码的秘诀了呢?

在这里插入图片描述