专栏名称: 程序猿
本微信公众号:imkuqin,为程序员提供最新最全的编程学习资料的查询。目前已经开通PHP、C/C++函数库、.NET Framework类库、J2SE API查询功能。
目录
相关文章推荐
程序员小灰  ·  蔚来汽车裁员约10%,20分钟完成裁员。。。 ·  3 天前  
OSC开源社区  ·  地表最强「开源版PS」——GIMP ... ·  3 天前  
程序员的那些事  ·  65 ... ·  2 天前  
51好读  ›  专栏  ›  程序猿

你知道 Python 这五个有趣的彩蛋吗?

程序猿  · 公众号  · 程序员  · 2017-08-01 16:00

正文

文章转载自 开源中国社区 [http://www.oschina.net]

链接:https://www.oschina.net/news/85139/top-5-python-easter-eggs-and-hidden-features (点击尾部阅读原文前往)

原文:http://www.eversql.com/top-5-python-easter-eggs-and-hidden-features/



当一门编程语言是开源的时候,往往会有产生一些搞笑和有趣的东西。通常,这意味着社区的贡献者会为该语言添加一些有趣和特别的彩蛋以及隐藏的特性(当然前提是不会增加在生产环境中使用的风险)。


Python 就是一个很好的例子。作为一门开源的语言,它的社区为其贡献了一些十分幽默的东西。


旁注:如果您想观察彩蛋,请注意,它们只能在第一次工作。如果希望重新运行它们,需要重新启动 Python shell。


0. Hello World


程序员们都熟悉 Hello World 的概念。在大多数情况下,它指的是使用该编程语言编写的最小程序,它会将“Hello World”打印到屏幕。这可能是在学习新的编程语言时首先要做的。


Python 有一个酷酷的隐藏的库,做了一些有点与众不同的事:

>>> import __hello__   
Hello World...

1、April Fool


下面的 April fool 玩笑是由 Barry Warsaw 提出的,与他的退休有关。他是一位著名的 Python 开发者,在他宣布正式退休的时候,就诞生了下面这个彩蛋:

>>> from __future__ import barry_as_FLUFL   
>>> 1 <> 2   

True

2、由 C++ 转换到 Python


'braces'库也是一个具有浓厚程序员风格的玩笑,它在其文档中提到,当在编写 Python 代码时使用这个库可提供使用 C++ 花括号的功能。但当你尝试使用它的时候,你将会看到社区对此的看法:

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

哈哈哈,以为导入 braces 就可以使用花括号来结束代码块?Python 的答案是:没门儿!


3、经典的 Python 之禅

import this

运行此命令将显示由 Tim Peters 编写的"Zen Of Python(Python 之禅)"。据传这是 Python 中的『八荣八耻』,每个有追求的 Python 程序员都应该谨记于心。

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.   
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!

参考翻译:







请到「今天看啥」查看全文