?
經(jīng)常逛GitHub的可能關(guān)注一個(gè)牛叉的項(xiàng)目,叫 What the f*ck Python!
這個(gè)項(xiàng)目列出了幾乎所有python中那些鮮為人知的功能特性郑临,有些功能第一次遇見時(shí)据过,你會(huì)冒出 what the f**k 的感嘆惋砂。
因?yàn)檫@些例子看起來反人類直覺。
但是如果你理解了它背后的真正原理绳锅,你又會(huì)驚嘆what the f**k西饵, 竟然還有這么騷的操作。
來看看幾個(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ù)制代碼
說好的元組不可變呢
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…
最后多說一句积蜻,想學(xué)習(xí)Python可聯(lián)系小編,這里有我自己整理的整套python學(xué)習(xí)資料和路線彻消,想要這些資料的都可以進(jìn)q裙930900780領(lǐng)取竿拆。
本文章素材來源于網(wǎng)絡(luò),如有侵權(quán)請(qǐng)聯(lián)系刪除宾尚。