#!/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.

它如何工作
這是一個(gè)很長(zhǎng)的例子,但是它有助于說(shuō)明類與對(duì)象的變量的本質(zhì)。這里,population屬于Person
類,因此是一個(gè)類的變量。name變量屬于對(duì)象(它使用self賦值)因此是對(duì)象的變量。
觀察可以發(fā)現(xiàn)__init__方法用一個(gè)名字來(lái)初始化Person實(shí)例。在這個(gè)方法中,我們讓population
增加1,這是因?yàn)槲覀冊(cè)黾恿艘粋€(gè)人。同樣可以發(fā)現(xiàn),self.name的值根據(jù)每個(gè)對(duì)象指定,這表
明了它作為對(duì)象的變量的本質(zhì)。
記住,你只能使用self變量來(lái)參考同一個(gè)對(duì)象的變量和方法。這被稱為 屬性參考 。
在這個(gè)程序中,我們還看到docstring對(duì)于類和方法同樣有用。我們可以在運(yùn)行時(shí)使用Person.
__doc__和Person.sayHi.__doc__來(lái)分別訪問(wèn)類與方法的文檔字符串。
就如同__init__方法一樣,還有一個(gè)特殊的方法__del__,它在對(duì)象消逝的時(shí)候被調(diào)用。對(duì)象消
逝即對(duì)象不再被使用,它所占用的內(nèi)存將返回給系統(tǒng)作它用。在這個(gè)方法里面,我們只是簡(jiǎn)單
地把Person.population減1。
當(dāng)對(duì)象不再被使用時(shí),__del__方法運(yùn)行,但是很難保證這個(gè)方法究竟在 什么時(shí)候 運(yùn)行。如果
你想要指明它的運(yùn)行,你就得使用del語(yǔ)句,就如同我們?cè)谝郧暗睦又惺褂玫哪菢印?br>給C++/Java/C#程序員的注釋
Python中所有的類成員(包括數(shù)據(jù)成員)都是 公共的 ,所有的方法都是 有效的 。
只有一個(gè)例外:如果你使用的數(shù)據(jù)成員名稱以 雙下劃線前綴 比如__privatevar,Python的名稱
管理體系會(huì)有效地把它作為私有變量。
這樣就有一個(gè)慣例,如果某個(gè)變量只想在類或?qū)ο笾惺褂茫蛻?yīng)該以單下劃線前綴。而其他的
名稱都將作為公共的,可以被其他類/對(duì)象使用。記住這只是一個(gè)慣例,并不是Python所要求
的(與雙下劃線前綴不同)。
同樣,注意__del__方法與 destructor 的概念類似。