1. 程式人生 > 程式設計 >Python 中隱藏的彩蛋們

Python 中隱藏的彩蛋們

這是一個 Python 中隱藏的彩蛋和笑話列表。如果你還知道其他有趣的彩蛋和笑話,歡迎在 GitHub 上建立 PR 新增。

專案地址:https://github.com/greyli/shedan

Python 比你想象中的更有趣。



A little girl goes into a pet shop and asks for a wabbit. The shop keeper looks down at her,smiles and says:

"Would you like a lovely fluffy little white rabbit,or a cutesy wootesly little brown rabbit?"

"Actually",says the little girl,"I don't think my python would notice."

—Nick Leaton,Wed,04 Dec 1996,Python Humor

1. Hello World

>>> import __hello__
Hello World!複製程式碼
Note:在 Python 中列印「Hello,World!」最簡單的方式。

2. 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!複製程式碼
Note:Python 設計哲學 & Python 程式碼風格指南。

3. 《Python 之禪》丟失的一行

《Python 之禪》在 PEP 20 中引入,它本應該是 20 條格言,但是最終只寫了 19 條。

Note:也許只是為了說明在檔案的結尾總是應該保留一個空行。

4. 一堂簡單的人生課

>>> import this
...
>>> love = this
>>> this is love
True
>>> love is True
False
>>> love is False
False
>>> love is not True or False
True
>>> love is not True or False; love is love  # FML
True複製程式碼
Note:不是彩蛋,只是一個直譯器裡的玩笑。

5. 反重力漫畫

>>> import antigravity複製程式碼
Note:這會開啟這個 xkcd 漫畫,漫畫展示了 Python 有多麼簡單易學。

6. 這不是一個選擇,它定義了我們是誰

>>> from __future__ import braces
  File "<stdin>",line 1
SyntaxError: not a chance複製程式碼
Note:這用來快速結束任何關於在 Python 中引入大括號的討論——不可能!

7. 起源

「Python」這個名字和蛇的種類沒有關係。

Note:實際的來源是 Guido van Rossum 喜歡的電視劇《Monty Python's Flying Circus》。

8. 反差

下面是打印出《Python 之禪》的 this.py 模組的內容:

s = """Gur Mra bs Clguba,ol Gvz Crgref

Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyrk.
Pbzcyrk vf orggre guna pbzcyvpngrq.
Syng vf orggre guna arfgrq.
Fcnefr vf orggre guna qrafr.
Ernqnovyvgl pbhagf.
Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.
Nygubhtu cenpgvpnyvgl orngf chevgl.
Reebef fubhyq arire cnff fvyragyl.
Hayrff rkcyvpvgyl fvyraprq.
Va gur snpr bs nzovthvgl,ershfr gur grzcgngvba gb thrff.
Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.
Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.
Abj vf orggre guna arire.
Nygubhtu arire vf bsgra orggre guna *evtug* abj.
Vs gur vzcyrzragngvba vf uneq gb rkcynva,vg'f n onq vqrn.
Vs gur vzcyrzragngvba vf rnfl gb rkcynva,vg znl or n tbbq vqrn.
Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!"""

d = {}
for c in (65,97):
    for i in range(26):
        d[chr(i+c)] = chr((i+13) % 26 + c)

print("".join([d.get(c,c) for c in s]))複製程式碼

生成《Python 之禪》的程式碼本身違背了自己宣揚的風格建議。它醜陋而不美麗,隱式而不直觀。

Note:使用了一種叫 ROT13 的置換加密法。

9. 有沒有 C/C++ 使用者?

再次引用《Python 之禪》:

There should be one-- and preferably only one --obvious way to do it.複製程式碼
Note:在很多語言裡常常有兩種方法做同一件事,即 --nono--。這一行包含了一個隱藏的示例。

10. 命名識別符號可以非常酷

>>> from math import pi
>>> π = pi
>>> area = π * r**2

>>> résumé = 'knows Python'
>>> 'Python' in résumé
True

>>> 我的英文名 = 'Grey Li'
>>> 我的英文名
'Grey Li'

>>> import webbrowser
>>> 我的網站 = 'http://greyli.com'
>>> webbrowser.open(我的網站)複製程式碼
Note:Python 3 中支援使用 Unicode 字元作為變數名。儘管如此,使用非英文字元作為變數名可能不是一個好主意,不過它確實會讓處理科學公式的工作變得更有意思。

11. 選一個見面地點

>>> from antigravity import geohash
>>> # Your location,a date and that date's (or most recent) DJIA opening.
>>> # 你的位置,一個日期和這個日期(或最近)對應的道瓊斯工業指數。
>>> geohash(37.421542,-122.085589,b'2005-05-26-10458.68')
37.857713 -122.544543複製程式碼

這可以用來生成一個 GPS 定位,在基於你所在位置的一個 1 經度長和 1 緯度寬的區域裡。

Note:這個函式的原始碼在 這裡,工作原理解釋可以在這個 xkcd 漫畫看到,也許這就是為什麼這個函式也放到了 antigravity 模組裡。

12. The FLUFL - Friendly Language Uncle For Life from PEP 401 -- BDFL Retirement

>>> from __future__ import barry_as_FLUFL
>>> 1 <> 2
True
>>> 1 != 2
  File "<stdin>",line 1
    1 != 2
       ^
SyntaxError: invalid syntax複製程式碼

在認識到 Python 3.0 的不等運運算元(!=)非常糟糕,是手指疼痛導致的錯誤後,FLUFL(指 Uncle Barry)重新恢復鑽石型操作符(<>)作為唯一的不等運運算元拼寫。

Note:PEP 401 是一個愚人節玩笑(從編號可以看出來)。這個 PEP 宣告 Guido van Rossum 要退休了。他會獲得一個新的頭銜,叫做「BDEVIL」(Benevolent Dictator Emeritus Vacationing Indefinitely from the Language,去度無限期語言假期的仁慈退休獨裁者),接任者將會是 Barry Warsaw(即 Uncle Barry),Uncle Barry 的官方頭銜是「FLUFL」(Friendly Language Uncle For Life,終生友好語言叔叔)。

13. InPynite?

>>> infinity = float('infinity')
>>> hash(infinity)
314159
>>> hash(float('-inf'))
-314159複製程式碼

一個雜湊值是一個固定尺寸的整型,它會標識一個特定的值。仔細觀察,你會發現雜湊值的無限大是 10^5 x π。有意思的是,在 Python3 中,hash(float('-inf')) 將會生成 -10^5 x π,而在 Python 2 中則是 -271828(即 10^5 x e)。

Note:來源

14. types.CodeType - Not for the faint of heart

如果你開始鑽進 Python 的內部,你會在 help 輸出看到一個關於 types.CodeType 的警告:不適合心臟脆弱者。

>>> import types
>>> help(types.CodeType)
...
Help on class code in module builtins:                                                    
                                                                                          
class code(object)                                                                        
 |  code(argcount,kwonlyargcount,nlocals,stacksize,flags,codestring,|        constants,names,varnames,filename,name,firstlineno,|        lnotab[,freevars[,cellvars]])                                                 
 |                                                                                        
 |  Create a code object.  Not for the faint of heart.                                    
 |                                                                                        
 |  Methods defined here:                                                                 
 |                                                                                                                                       
 ...複製程式碼

原始版本翻譯自 https://github.com/OrkoHunter/python-easter-eggs ,原專案沒有許可協議,已通過郵件申請獲得翻譯和釋出許可。