淺析面向對象的主要Python類
在Python中類是對某個對象的定義,它包含有關對象動作方式的信息,包括它的名稱、方法、屬性和事件,下面文章可以進一步的學習和了解關于Python類的問題,類這個問題大大的提高了變量的數(shù)據(jù)。
對象可以使用普通的屬于對象的變量存儲數(shù)據(jù)。屬于一個對象或Python類的變量被稱為域。對象也可以使用屬于類的函數(shù)來具有功能,這樣的函數(shù)被稱為類的方法。域和方法可以合稱為類的屬性。域有兩種類型--屬于每個實例(對象)的方法稱為實例變量;屬于類本身的稱為類變量。
類的方法和普通的函數(shù)只有一個特別的區(qū)別--他們必須有一個額外的***個參數(shù)名稱,但是在調用方法的時候你不為這個參數(shù)賦值,python會提供這個值。這個特別的變量指對象本身,按照慣例它的名稱為self。
類與對象的方法可以看一個例子來理解:
- 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類,因此是一個Python類的變量。name變量屬于對象(它使用self賦值)因此是對象的變量。 觀察可以發(fā)現(xiàn)__init__方法用一個名字來初始化Person實例。在這個方法中,我們讓population增加1,這是因為我們增加了一個人。
同樣可以發(fā)現(xiàn),self.name的值根據(jù)每個對象指定,這表明了它作為對象的變量的本質。 記住,你只能使用self變量來參考同一個對象的變量和方法。這被稱為 屬性參考 。
【編輯推薦】