《Python之禅》让我们的python代码更加优美

之前在另外一篇文章中有总结过一部分关于python命名的规范,也帮助到了一些小伙伴,今天这篇文章主要是分享下《Python之禅》

历史文章跳转:python常用命名规范_python命名规范_花生君的博客-CSDN博客

查看《The Zen of Python》方法:

解释器中 import this

直接运行后,控制台输出英文版《The Zen of 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!

中文翻译:

Python之禅  作者:Tim Peters

优美胜于丑陋

明了胜于晦涩

扫描二维码关注公众号,回复: 17226455 查看本文章

简洁胜于复杂

复杂胜于凌乱

扁平胜于嵌套

间隔胜于紧凑

可读性很重要

即便假借特例的实用性之名,也不可违背这些规则

不要包容所有错误,除非你确定需要这样做

当存在多种可能,不要尝试去猜测

而是尽量找一种,最好是唯一一种明显的解决方案

虽然这并不容易,因为你不是 Python 之父

做也许好过不做,但不假思索就动手还不如不做

如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然

命名空间是一种绝妙的理念,我们应当多加利用

理解释义:

Python 以编写优美的代码为目标

优美的代码应当是明了的,命名规范,风格相似

优美的代码应当是简洁的,不要有复杂的内部实现

如果复杂不可避免,那代码间也不能有难懂的关系,要保持接口简洁

优美的代码应当是扁平的,不能有太多的嵌套

优美的代码有适当的间隔,不要奢望一行代码解决问题

优美的代码是可读的

精准地捕获异常,不写 except:pass 风格的代码

PS:在PyCharm中善用 ctrl+alt+L 快捷键,可以让代码快速格式化,方便阅读(大家都知道,但是有小伙伴习惯没有养成,特此提醒)

猜你喜欢

转载自blog.csdn.net/m0_54701273/article/details/131229735