有兩種類型的 域 ——類的變量和對象的變量,它們根據是類還是對象 擁有 這個變量而區分。
類的變量 由一個類的所有對象(實例)共享使用。只有一個類變量的拷貝,所以當某個對象對類的變量做了改動的時候,這個改動會反映到所有其他的實例上。
對象的變量 由類的每個對象/實例擁有。因此每個對象有自己對這個域的一份拷貝,即它們不是共享的,在同一個類的不同實例中,雖然對象的變量有相同的名稱,但是是互不相關的。通過一個例子會使這個易於理解。
程序
------------------------------------------------------------------------------------------------------
#!/usr/bin/python
# Filename: objvar.py
class Person:
'''Represents a person.'''
population = 0類的變量
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
def __del__(self):
'''I am dying.'''
print '%s says bye.' % self.name
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):
'''Greeting by the person.
Really, that's all it does.'''
print 'Hi, my name is %s.' % self.name
def howMany(self):
'''Prints the current population.'''
if Person.population == 1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' % Person.population
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
--------------------------------------------------------------------------------------------------------
輸出
--------------------------------------------------------------------------------------------------------
$ python objvar.py
(Initializing Swaroop)
Hi, my name is Swaroop.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Hi, my name is Swaroop.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.
--------------------------------------------------------------------------------------------------------
這裏,population屬於Person類,因此是一個類的變量。name變量使用self賦值,因此是對象的變量。
__init__方法用一個名字來初始化Person實例。在這個方法中,我們讓population增加1,這是因爲我們增加了一個人。同樣可以發現,self.name的值根據每個對象指定,這表明了它作爲對象的變量的本質。
記住,你只能使用self變量來參考同一個對象的變量和方法。這被稱爲 屬性參考 。
在這個程序中,我們還看到docstring對於類和方法同樣有用。我們可以在運行時使用Person.__doc__和Person.sayHi.__doc__來分別訪問類與方法的文檔字符串。
有一個特殊的方法__del__,它在對象消逝的時候被調用。這就是python類的析構函數。當對象不再被使用,它所佔用的內存將返回給系統。在這個方法裏面,我們只是簡單地把Person.population減1。
當對象不再被使用時,__del__方法運行,但是很難保證這個方法究竟在 什麼時候 運行。如果你想要指明它的運行,你就得使用del語句。
Python中所有的類成員(包括數據成員)都是 公共的 。
只有一個例外:如果你使用的數據成員名稱以 雙下劃線前綴 比如__privatevar,Python的名稱管理體系會有效地把它作爲私有變量。
這樣就有一個慣例,如果某個變量只想在類或對象中使用,就應該以單下劃線前綴。而其他的名稱都將作爲公共的,可以被其他類/對象使用。記住這只是一個慣例,並不是Python所要求的(與雙下劃線前綴不同)。(這裏有問題)