常常逛GitHub的可能關注一個牛叉的項目,叫 What the f*ck Python!python
這個項目列出了幾乎全部python中那些不爲人知的功能特性,有些功能第一次碰見時,你會冒出 what the f**k 的感嘆。git
由於這些例子看起來反人類直覺。github
可是若是你理解了它背後的真正原理,你又會驚歎what the f**k, 居然還有這麼騷的操做。web
來看看幾個例子吧。app
>>> a = "wtf"
>>> b = "wtf"
>>> a is b
True
>>> a = "wtf!"
>>> b = "wtf!"
>>> a is b
False
>>> a, b = "wtf!", "wtf!"
>>> a is b
True # 3.7 版本返回結果爲 False.
複製代碼
>>> a = 256
>>> b = 256
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False
>>> a = 257; b = 257
>>> a is b
True
複製代碼
some_tuple = ("A", "tuple", "with", "values")
another_tuple = ([1, 2], [3, 4], [5, 6])
>>> some_tuple[2] = "change this"
TypeError: 'tuple' object does not support item assignment
>>> another_tuple[2].append(1000) # 這裏不出現錯誤
>>> another_tuple
([1, 2], [3, 4], [5, 6, 1000])
>>> another_tuple[2] += [99, 999]
TypeError: 'tuple' object does not support item assignment
>>> another_tuple
([1, 2], [3, 4], [5, 6, 1000, 99, 999])
複製代碼
e = 7
try:
raise Exception()
except Exception as e:
pass
複製代碼
輸出this
>>> print(e)
NameError: name 'e' is not defined
複製代碼
def some_func():
try:
return 'from_try'
finally:
return 'from_finally'
複製代碼
輸出spa
>>> some_func()
'from_finally'
複製代碼
諸如此類的例子一共有50多個code
若是你能把這50多個特性背後的原理機制所有了解清楚,我相信你的python功力必定會上升一個層次。orm
傳送門: github.com/leisurelich…cdn
文章首發公衆號:python之禪,歡迎關注