GitHub 標(biāo)星 20K+:What the fuck Python?!
經(jīng)常逛GitHub的可能關(guān)注一個(gè)牛叉的項(xiàng)目,叫 What the f*ck Python!
這個(gè)項(xiàng)目列出了幾乎所有python中那些鮮為人知的功能特性,有些功能第一次遇見(jiàn)時(shí),你會(huì)冒出 what the f**k 的感嘆。
因?yàn)檫@些例子看起來(lái)反人類(lèi)直覺(jué)。
但是如果你理解了它背后的真正原理,你又會(huì)驚嘆what the f**k, 竟然還有這么騷的操作。
來(lái)看看幾個(gè)例子吧。
微妙的字符串
>>> 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 版本返回結(jié)果為 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說(shuō)好的元組不可變呢
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) # 這里不出現(xiàn)錯(cuò)誤
>>> 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 definedtry 遇到 finally到底返回哪個(gè)值
def some_func():
try:
return 'from_try'
finally:
return 'from_finally'輸出
>>> some_func()
'from_finally'諸如此類(lèi)的例子一共有50多個(gè),

如果你能把這50多個(gè)特性背后的原理機(jī)制全部了解清楚,我相信你的python功力一定會(huì)上升一個(gè)層次。
傳送門(mén): https://github.com/leisurelicht/wtfpython-cn
關(guān)注我,每天分享實(shí)用小知識(shí)
評(píng)論
圖片
表情
