第一種用途:在循環(huán)中土铺,不想給循環(huán)變量起名字,可以用"_",例如:
for _ in range(5):
print(_)
0
1
2
3
4
第二種用途:在解包表達(dá)式中板鬓,對(duì)于不在乎(don't care)的變量悲敷,即可以忽略的元素,連存儲(chǔ)其變量的名字都不想取俭令,可以用"_",例如:
fruits = {'Yellow':['Banana','Mango'], 'Green':['Grapes','Guava'],'Red':['Apple','Cherry']}
_,_,red_fruits = fruits.values()
>>> red_fruits
['Apple','Cherry']
>>> _
['Grapes','Guava']
第三種用途:?jiǎn)蝹€(gè)前導(dǎo)下劃線后德,表示變量供內(nèi)部使用,例如:
>>> class Fruits:
... def __init__(self):
... self.variety = 30
... self._stock = "50 crates of each variety"
... def _stage(self):
... print("All fruits are fully ripe")
...
>>> check_fruits = Fruits()
>>> check_fruits.variety
30
>>> check_fruits._stock
'50 crates of each variety'
>>> check_fruits._stage()
All fruits are fully ripe
>>>
第四種用途:?jiǎn)蝹€(gè)后導(dǎo)下劃線抄腔,當(dāng)必須使用已經(jīng)被Python使用的關(guān)鍵字(keyword)時(shí)探遵,為了避免命名沖突,可以加單個(gè)后導(dǎo)下劃線妓柜,例如:class是關(guān)鍵字箱季,用戶可以使用class_
第五種用途:雙前導(dǎo)下劃線,解釋器會(huì)自動(dòng)在其名稱前加入當(dāng)前類名棍掐,以避免命名沖突藏雏,例如:
雙前導(dǎo)下劃線
第六種用途:雙前后下劃線的方法是 Python 中稱為“魔術(shù)方法”或“dunder 方法”的特殊方法,當(dāng)滿足某些條件時(shí)作煌,Python解釋器會(huì)自動(dòng)調(diào)用它們掘殴,例如:__ init __(),對(duì)象在創(chuàng)建時(shí)粟誓,Python解釋器會(huì)自動(dòng)調(diào)用init()方法奏寨。
魔術(shù)方法由Python解釋器自動(dòng)調(diào)用