看到Python中有個函數名比較奇特,__init__我知道加下劃線的函數會自動運行,但是不知道它存在的具體意義..
Python中所有的類成員(包括數據成員)都是公共的,所有的方法都是有效的。
只有一個例外:如果你使用的數據成員名稱以雙下劃線前綴比如__privatevar,Python的名稱管理體系會有效地把它作為私有變量。
這樣就有一個慣例,如果某個變量只想在類或對象中使用,就應該以單下劃線前綴。而其他的名稱都將作為公共的,可以被其他類/對象使用。記住這只是一個慣例,并不是Python所要求的(與雙下劃線前綴不同)。
同樣,注意__del__方法與destructor的概念類似。"
恍然大悟原來__init__在類中被用做構造函數,固定寫法,看似很死板,其實有道理
def__init__(self,name):
'''Initializestheperson'sdata.'''
self.name=name
print'(Initializing%s)'%self.name
#Whenthispersoniscreated,he/she
#addstothepopulation
Person.population+=1
name變量屬于對象(它使用self賦值)因此是對象的變量
self.name的值根據每個對象指定,這表明了它作為對象的變量的本質。
例如我們定義一個Box類,有width,height,depth三個屬性,以及計算體積的方法:
classBox:
defsetDimension(self,width,height,depth):
self.width=width
self.height=height
self.depth=depth
defgetVolume(self):
returnself.width*self.height*self.depth
b=Box()
b.setDimension(10,20,30)
print(b.getVolume())
我們在Box類中定義了setDimension方法去設定該Box的屬性,這樣過于繁瑣,而用__init__()這個特殊的方法就可以方便地自己對類的屬性進行定義,__init__()方法又被稱為構造器(constructor)。
classBox:
#defsetDimension(self,width,height,depth):
#self.width=width
#self.height=height
#self.depth=depth
def__init__(self,width,height,depth):
self.width=width
self.height=height
self.depth=depth
defgetVolume(self):
returnself.width*self.height*self.depth
b=Box(10,20,30)
print(b.getVolume())
以上內容為大家介紹了Python培訓之__init__到底是干什么的?,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。