淺析面向?qū)ο蟮闹饕狿ython類
在Python中類是對(duì)某個(gè)對(duì)象的定義,它包含有關(guān)對(duì)象動(dòng)作方式的信息,包括它的名稱、方法、屬性和事件,下面文章可以進(jìn)一步的學(xué)習(xí)和了解關(guān)于Python類的問題,類這個(gè)問題大大的提高了變量的數(shù)據(jù)。
對(duì)象可以使用普通的屬于對(duì)象的變量存儲(chǔ)數(shù)據(jù)。屬于一個(gè)對(duì)象或Python類的變量被稱為域。對(duì)象也可以使用屬于類的函數(shù)來具有功能,這樣的函數(shù)被稱為類的方法。域和方法可以合稱為類的屬性。域有兩種類型--屬于每個(gè)實(shí)例(對(duì)象)的方法稱為實(shí)例變量;屬于類本身的稱為類變量。
類的方法和普通的函數(shù)只有一個(gè)特別的區(qū)別--他們必須有一個(gè)額外的***個(gè)參數(shù)名稱,但是在調(diào)用方法的時(shí)候你不為這個(gè)參數(shù)賦值,python會(huì)提供這個(gè)值。這個(gè)特別的變量指對(duì)象本身,按照慣例它的名稱為self。
類與對(duì)象的方法可以看一個(gè)例子來理解:
- class Person:
- population=0
- def __init__(self,name):
- self.name=name
- Person.population+=1
- def __del__(self):
- Person.population -=1
- if Person.population==0:
- print("i am the last one")
- else:
- print("There are still %d people left."%Person.population)
- def sayHi(self):
- print("hi my name is %s"%self.name)
- def howMany(self):
- if Person.population==1:
- print("i am the only person here")
- else:
- print("we have %d persons here."%Person.population)
- s=Person("jlsme")
- s.sayHi()
- s.howMany()
- k=Person("kalam")
- k.sayHi()
- k.howMany()
- s.sayHi()
- s.howMany()
- 輸出:
- hi my name is jlsme
- i am the only person here
- hi my name is kalam
- we have 2 persons here.
- hi my name is jlsme
- we have 2 persons here.
population屬于Python類,因此是一個(gè)Python類的變量。name變量屬于對(duì)象(它使用self賦值)因此是對(duì)象的變量。 觀察可以發(fā)現(xiàn)__init__方法用一個(gè)名字來初始化Person實(shí)例。在這個(gè)方法中,我們讓population增加1,這是因?yàn)槲覀冊(cè)黾恿艘粋€(gè)人。
同樣可以發(fā)現(xiàn),self.name的值根據(jù)每個(gè)對(duì)象指定,這表明了它作為對(duì)象的變量的本質(zhì)。 記住,你只能使用self變量來參考同一個(gè)對(duì)象的變量和方法。這被稱為 屬性參考 。
【編輯推薦】