下劃線(xiàn)在 Python 中的特殊含義
點(diǎn)擊上方“小白學(xué)視覺(jué)”,選擇加"星標(biāo)"或“置頂”
重磅干貨,第一時(shí)間送達(dá)
下劃線(xiàn)在 Python 中是有特殊含義的,它們?cè)?Python 的不同地方使用。
下面是 Python 中使用的不同類(lèi)型的下劃線(xiàn):


保存上次執(zhí)行的表達(dá)式的值
使用一個(gè)下劃線(xiàn)保存 Python 交互式命令提示符中最后執(zhí)行的表達(dá)式的值。我們還可以將值保存到另一個(gè)變量。

在循環(huán)中忽略值
在 Python 中使用一個(gè)下劃線(xiàn) _ 來(lái)忽略某些值。如果我們不想使用某些值,我們可以給將該值賦值給 _ 。
#Single underscore used in for loopfor _ in range(5):print ("Python")'''Output:PythonPythonPythonPythonPython'''#Iterating through listcolors=["red","blue","green"]for _ in colors:print (_)'''Output:redbluegreen'''
忽略元組解壓縮中的值
如果在元組解壓縮時(shí)想要忽略某些值,可以將這些值分配給 _。
#tuple unpackingt=("red","green","blue")#ignoring value "green" while tuple unpackingt1,_,t2=tprint (t1)#Output:redprint (t2)#Output:blue#Ignoring multiple values in tuple unpackingtt=(1,2,3,4,5,6)#Ignoring all values except first and last element in tuple.t3,*_,t4=ttprint (t3)print (t4)
用于數(shù)字分隔符
下劃線(xiàn)也可以用作數(shù)字的分隔符,用于整數(shù)、浮點(diǎn)數(shù)和復(fù)數(shù)等數(shù)值中的數(shù)字分組。下劃線(xiàn)沒(méi)有語(yǔ)義含義,并且文字被解析,就像沒(méi)有下劃線(xiàn)一樣。
#grouping decimal numbers by _a=10_000_000print (a)#Output:10000000
可以在變量名、方法名和類(lèi)名中使用單個(gè)前綴下劃線(xiàn)。它表示這些帶有一個(gè)前綴下劃線(xiàn)的類(lèi)、變量和方法名稱(chēng)被程序視為“私有”。如果我們從 from M import * 中指定,那些以單個(gè)前綴下劃線(xiàn)開(kāi)頭的名稱(chēng)將不會(huì)被導(dǎo)入。如果我們想導(dǎo)入這些變量/方法,我們必須在導(dǎo)入時(shí)指定名稱(chēng)。
引用 PEP-8:
_single_leading_underline:弱“ internal use” 指示符。例如:from m import * 不導(dǎo)入名稱(chēng)以下劃線(xiàn)開(kāi)頭的對(duì)象。
#variable name having single leading underscore._a="hello"b="helloworld"def add(x,y):print (x+y)#function name having single leading underscoredef _sub(x,y):print (x-y)if __name__ == '__main__':print (_a)#Output:helloadd(4,3)#Output:7_sub(4,3)#Output:1
將上面提到的 Python 文件 c1.py import 至 c2.py
示例:from c1 import *
只有一個(gè)前綴下劃線(xiàn)的變量和函數(shù)不能被訪(fǎng)問(wèn)。
from c1 import *#accessing variable names having single leading underscore.print (_a)#Output:NameError: name '_a' is not defined#accessing function name havig single leading underscoreprint (_sub(7,2))#Output:NameError: name '_sub' is not defined#accessing variables and functions which is not having single leading underscore.# we will able to access those varaibles and functionsadd(3,4)#Output:7print (b)#helloworld
如果我們想導(dǎo)入只有一個(gè)前綴下劃線(xiàn)的變量和函數(shù),那么在導(dǎo)入時(shí)必須提到這個(gè)變量名。
例如:from c1 import _a,_sub
from c1 import _a,_sub#accessing variable names having single leading underscore.print (_a)#Output:hello#accessing function name having single leading underscore_sub(7,2)#Output:5
單個(gè)后綴下劃線(xiàn)用于避免與 Python 關(guān)鍵字沖突。
引用 PEP-8:
約定使用 single_trailing_underline_: 以避免與 Python 關(guān)鍵字沖突
list=[1,2,3]t=(5,6,7)#Coverting tuple to list using list() constructort1=list(t)#Output:TypeError: 'list' object is not callable
在上面的示例中,我們可以使用 list_ 作為變量名,以避免與 Python 關(guān)鍵字 list 發(fā)生沖突。
list_=[1,2,3]t=(5,6,7)#Coverting tuple to list using list() constructort1=list(t)print (t1)#Output:[5, 6, 7]
雙下劃線(xiàn)告訴 Python 解釋器重寫(xiě)子類(lèi)的屬性名和方法名,以避免命名沖突。用類(lèi)擴(kuò)展名更改屬性名稱(chēng)的解釋器稱(chēng)為名稱(chēng)改寫(xiě)。
用 self._classname__methodname()代替 self.__methodname(),用
self._classname__attributename 代替 self.__attributename。
根據(jù) Python 文檔:
“名稱(chēng)改寫(xiě)有助于讓子類(lèi)重寫(xiě)方法,而不會(huì)破壞類(lèi)內(nèi)的方法調(diào)用。”
引用 PEP-8:
“ __double_leading_underline:當(dāng)命名一個(gè) class 屬性時(shí),調(diào)用名稱(chēng)改寫(xiě)(在類(lèi) FooBar 中,__boo 變成 _FooBar__boo)”
class Student:def __init__(self,name,rollno):self.name=nameself.__rollno=rollnodef __repr__(self):return "{},{}".format(self.name,self.rollno)s=Student("Karthi",12)print (s.name)#Unable to access attributes having leading double underscore.print (s.__rollno)#Output:AttributeError: 'Student' object has no attribute '__rollno'#Name Mangling - have to use class extension with variable nameprint (s._Student__rollno)#Output: 12
具有相同方法名的繼承類(lèi):
class A:def __getmethod(self):print ("Inside Class A")class B(A):def __getmethod(self):print ("Inside Class B")b=B()#Accessing __getmethod() in Class A using Name Manglingb._A__getmethod()#Output:Inside Class A#Accessing __getmethod() in Class B using Name Manglingb._B__getmethod()#Output:Inside Class B
Python 中的特殊方法以雙前綴和雙后綴下劃線(xiàn)命名。它們?cè)?Python 中被稱(chēng)為 magic methods/dunder methods 方法。
例如:__init__,__str__,__repr__,__len__,這些神奇的方法在 Python 中有特殊的意義,我們可以覆蓋它們來(lái)改變我們的類(lèi)的特性。
引用 PEP-8:
__double_leading_and_trailing_underscore__:“ magic”對(duì)象或?qū)傩裕挥谟脩?hù)控制的名稱(chēng)空間中。例如 __init__,?__import__ 或 __file__。永遠(yuǎn)不要發(fā)明這樣的名稱(chēng),只能根據(jù)記錄使用。
根據(jù) Python 約定,避免使用具有雙前綴和雙后綴下劃線(xiàn)的變量名。
我們可以使用 dir()函數(shù)來(lái)查看類(lèi)繼承的神奇方法。
class Student:def __init__(self,name,rollno):self.name=nameself.rollno=rollnodef __repr__(self):return "{},{}".format(self.name,self.rollno)s=Student("karthi",12)print (s)#Output:karthi,12print (dir(Student))'''Output:['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_'''
交流群
歡迎加入公眾號(hào)讀者群一起和同行交流,目前有SLAM、三維視覺(jué)、傳感器、自動(dòng)駕駛、計(jì)算攝影、檢測(cè)、分割、識(shí)別、醫(yī)學(xué)影像、GAN、算法競(jìng)賽等微信群(以后會(huì)逐漸細(xì)分),請(qǐng)掃描下面微信號(hào)加群,備注:”昵稱(chēng)+學(xué)校/公司+研究方向“,例如:”張三?+?上海交大?+?視覺(jué)SLAM“。請(qǐng)按照格式備注,否則不予通過(guò)。添加成功后會(huì)根據(jù)研究方向邀請(qǐng)進(jìn)入相關(guān)微信群。請(qǐng)勿在群內(nèi)發(fā)送廣告,否則會(huì)請(qǐng)出群,謝謝理解~

