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)反人類直覺(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.

復(fù)制代碼

出乎意料的"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

復(fù)制代碼

說(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])

復(fù)制代碼

消失的全局變量

e = 7

try:

? ? raise Exception()

except Exception as e:

? ? pass

復(fù)制代碼

輸出

>>> print(e)

NameError: name 'e' is not defined

復(fù)制代碼

到底返回哪個(gè)值

def some_func():

? ? try:

? ? ? ? return 'from_try'

? ? finally:

? ? ? ? return 'from_finally'

復(fù)制代碼

輸出

>>> some_func()

'from_finally'

復(fù)制代碼

諸如此類的例子一共有50多個(gè)

?

如果你能把這50多個(gè)特性背后的原理機(jī)制全部了解清楚,我相信你的python功力一定會(huì)上升一個(gè)層次。

傳送門: github.com/leisurelich…

最后多說(shuō)一句,想學(xué)習(xí)Python可聯(lián)系小編,這里有我自己整理的整套python學(xué)習(xí)資料和路線,想要這些資料的都可以進(jìn)q裙930900780領(lǐng)取。

本文章素材來(lái)源于網(wǎng)絡(luò),如有侵權(quán)請(qǐng)聯(lián)系刪除。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容