新聞中心
看到Python中有個函數(shù)名比較奇特,__INIT__我知道加下劃線的函數(shù)會自動運行,但是不知道它存在的具體意義..

Python中所有的類成員(包括數(shù)據(jù)成員)都是 公共的 ,所有的方法都是 有效的 。
只有一個例外:如果你使用的數(shù)據(jù)成員名稱以 雙下劃線前綴 比如__privatevar,Python的名稱管理體系會有效地把它作為私有變量。
這樣就有一個慣例,如果某個變量只想在類或?qū)ο笾惺褂?,就?yīng)該以單下劃線前綴。而其他的名稱都將作為公共的,可以被其他類/對象使用。記住這只是一個慣例,并不是Python所要求的(與雙下劃線前綴不同)。
同樣,注意__del__方法與 destructor 的概念類似。"
恍然大悟原來__init__在類中被用做構(gòu)造函數(shù),固定寫法,看似很死板,其實有道理
def __init__(self, name): '''Initializes the person's data.''' self.name = name print '(Initializing %s)' % self.name # When this person is created, he/she # adds to the population Person.population += 1
name變量屬于對象(它使用self賦值)因此是對象的變量
self.name的值根據(jù)每個對象指定,這表明了它作為對象的變量的本質(zhì)。
例如我們定義一個Box類,有width, height, depth三個屬性,以及計算體積的方法:
class Box: def setDimension(self, width, height, depth): self.width = width self.height = height self.depth = depth def getVolume(self): return self.width * self.height * self.depth b = Box() b.setDimension(10, 20, 30) print(b.getVolume())
我們在Box類中定義了setDimension方法去設(shè)定該Box的屬性,這樣過于繁瑣,而用__init__()這個特殊的方法就可以方便地自己對類的屬性進行定義,__init__()方法又被稱為構(gòu)造器(constructor)。
class Box: #def setDimension(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 def getVolume(self): return self.width * self.height * self.depth b = Box(10, 20, 30) print(b.getVolume())
分享題目:創(chuàng)新互聯(lián)Python教程:Python中的__init__到底是干什么的?
本文地址:http://www.dlmjj.cn/article/ccehjoo.html


咨詢
建站咨詢
