Python反重力模块的目的

编码是一件极其严肃的事情,你要花时间独自在一个角落里对着键盘打代码,如果你最终能成功地构建应用程序,那么你还要处理bug,以及部署应用程序,这是一件无休止的苦差事。

值得庆幸的是,Python有办法用它自己的复活节彩蛋为我们打气。复活节彩蛋是指一部电影、游戏或应用程序有一个被发现的隐藏功能。

一个这样的 Python 复活节彩蛋是反重力模块。

让我们看看反重力模块的作用,并看看其他几个例子。

Python 反重力模块

如果乍一看,你认为 Python 反重力模块是为了让物品在你的 Python 应用程序中漂浮或悬浮而设计的,你不会被责备。

但它没有做这样的事情。创建一个 Python 文件并输入这些代码:

代码摘录-new.py:

import antigravity
def main():
	antigravity.fly()
 __name__=='__main__':
 main()

在你运行这个应用程序后,终端返回一个信息,说明:AttributeError: module 'antigravity' has no attribute 'fly'

然后它把你带到一个网站,上面有一段漫画对话,一个刚学会Python的人向一个朋友解释说它使他飞起来了。

SyntaxError: Not a Chance 在Python中

想象一下,试图运行一个应用程序,而你收到的错误信息是SyntaxError: not a chance 。这就是这个复活节产生的东西。

创建一个新文件,并输入这个片段。

代码片段-new.py:

from __future__ import braces
>>> SyntaxError: not a chance

使用Python Zen

最后但并非最不重要的是,传说中的Python的Zen。虽然这个特别的模块是一个复活节彩蛋,但它的教育性和娱乐性一样强,因为它是在Python中编码的准则。

打开一个新的Python文件,像这样输入这个片段:

Code Snippet-new.py:

>>> 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.
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.
It may be a good idea if the implementation is easy to explain.
Namespaces are one honking great idea -- let's do more of those!

结语

在Python框架中,有许多有趣的复活节彩蛋,可以帮助缓解漫长而枯燥的编码过程中的紧张感;在互联网上浏览一下,你会感到满意。