python中那些鮮為人知的功能特性

語言: CN / TW / HK

經常逛GitHub的可能關注一個牛叉的專案,叫 What the f*ck Python!

這個專案列出了幾乎所有python中那些鮮為人知的功能特性,有些功能第一次遇見時,你會冒出 what the f**k 的感嘆。

因為這些例子看起來反人類直覺。

但是如果你理解了它背後的真正原理,你又會驚歎what the f**k, 竟然還有這麼騷的操作。

來看看幾個例子吧。

微妙的字串

>>> 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.
複製程式碼

出乎意料的"is"

>>> 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
複製程式碼

輸出

>>> print(e)
NameError: name 'e' is not defined
複製程式碼

到底返回哪個值

def some_func():
    try:
        return 'from_try'
    finally:
        return 'from_finally'
複製程式碼

輸出

>>> some_func()
'from_finally'
複製程式碼

諸如此類的例子一共有50多個

如果你能把這50多個特性背後的原理機制全部瞭解清楚,我相信你的python功力一定會上升一個層次。

傳送門: github.com/leisurelich…

文章首發公眾號:python之禪,歡迎關注

http://user-gold-cdn.xitu.io/2017/7/16/4a84df1d3a79ea6aa60d4068ea549f6d?imageView2/0/w/1280/h/960/format/webp/ignore-error/1