#!/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__來分別訪問類與方法的文檔字符串。
就如同__init__方法一樣,還有一個特殊的方法__del__,它在對象消逝的時候被調用。對象消
逝即對象不再被使用,它所占用的內存將返回給系統作它用。在這個方法里面,我們只是簡單
地把Person.population減1。
當對象不再被使用時,__del__方法運行,但是很難保證這個方法究竟在 什么時候 運行。如果
你想要指明它的運行,你就得使用del語句,就如同我們在以前的例子中使用的那樣。
給C++/Java/C#程序員的注釋
Python中所有的類成員(包括數據成員)都是 公共的 ,所有的方法都是 有效的 。
只有一個例外:如果你使用的數據成員名稱以 雙下劃線前綴 比如__privatevar,Python的名稱
管理體系會有效地把它作為私有變量。
這樣就有一個慣例,如果某個變量只想在類或對象中使用,就應該以單下劃線前綴。而其他的
名稱都將作為公共的,可以被其他類/對象使用。記住這只是一個慣例,并不是Python所要求
的(與雙下劃線前綴不同)。
同樣,注意__del__方法與 destructor 的概念類似。