Python從設計之初就已經是一門物件導向的語言,正因為如此,在Python中建立一個類和對象是很容易的。本章節我們將詳細介紹Python的物件導向編程。
如果你以前沒有接觸過物件導向的程式設計語言,那你可能需要先瞭解一些物件導向語言的一些基本特徵,在頭腦裡頭形成一個基本的物件導向的概念,這樣有助於你更容易的學習Python的物件導向編程。
接下來我們先來簡單的瞭解下物件導向的一些基本特徵。
物件導向技術簡介
類(Class): 用來描述具有相同的屬性和方法的對象的集合。它定義了該集合中每個對象所共有的屬性和方法。對象是類的執行個體。
類變數:類變數在整個執行個體化的對象中是公用的。類變數定義在類中且在函數體之外。類變數通常不作為執行個體變數使用。
資料成員:類變數或者執行個體變數用於處理類及其執行個體對象的相關的資料。
方法重載:如果從父類繼承的方法不能滿足子類的需求,可以對其進行改寫,這個過程叫方法的覆蓋(override),也稱為方法的重載。
執行個體變數:定義在方法中的變數,只作用於當前執行個體的類。
繼承:即 一個衍生類別(derived class)繼承基類(base class)的欄位和方法。繼承也允許把一個衍生類別的對象作為一個基類對象對待。例如,有這樣一個設計:一個Dog類型的對象派生自Animal類,這是 類比"是一個(is-a)"關係(例圖,Dog是一個Animal)。
執行個體化:建立一個類的執行個體,類的具體對象。
方法:類中定義的函數。
對象:通過類定義的資料結構執行個體。對象包括兩個資料成員(類變數和執行個體變數)和方法。
建立類
使用class語句來建立一個新類,class之後為類的名稱並以冒號結尾,如下執行個體:
class ClassName:
'Optional class documentation string'#類文檔字串
class_suite #類體
類的協助資訊可以通過ClassName.__doc__查看。
class_suite 由類成員,方法,資料屬性群組成。
執行個體
以下是一個簡單的Python類執行個體:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
empCount變數是一個類變數,它的值將在這個類的所有執行個體之間共用。你可以在內部類或外部類使用Employee.empCount訪問。
第一種方法__init__()方法是一種特殊的方法,被稱為類的建構函式或初始化方法,當建立了這個類的執行個體時就會調用該方法
建立執行個體對象
要建立一個類的執行個體,你可以使用類的名稱,並通過__init__方法接受參數。
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
訪問屬性
您可以使用點(.)來訪問對象的屬性。使用如下類的名稱訪問類變數:
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
完整執行個體:
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
執行以上代碼輸出結果如下:
Name : Zara ,Salary: 2000
Name : Manni ,Salary: 5000
Total Employee 2
你可以添加,刪除,修改類的屬性,如下所示:
emp1.age = 7 # 添加一個 'age' 屬性
emp1.age = 8 # 修改 'age' 屬性
del emp1.age # 刪除 'age' 屬性
你也可以使用以下函數的方式來訪問屬性:
getattr(obj, name[, default]) : 訪問對象的屬性。
hasattr(obj,name) : 檢查是否存在一個屬性。
setattr(obj,name,value) : 設定一個屬性。如果屬性不存在,會建立一個新屬性。
delattr(obj, name) : 刪除屬性。
hasattr(emp1, 'age') # 如果存在 'age' 屬性返回 True。
getattr(emp1, 'age') # 返回 'age' 屬性的值
setattr(emp1, 'age', 8) # 添加屬性 'age' 值為 8
delattr(empl, 'age') # 刪除屬性 'age'
Python內建類屬性
__dict__ : 類的屬性(包含一個字典,由類的資料屬性群組成)
__doc__ :類的文檔字串
__name__: 類名
__module__: 類定義所在的模組(類的全名是'__main__.className',如果類位於一個匯入模組mymod中,那麼className.__module__ 等於 mymod)
__bases__ : 類的所有父類構成元素(包含了以個由所有父類組成的元組)
Python內建類屬性調用執行個體如下:
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__
執行以上代碼輸出結果如下:
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}
python對象銷毀(記憶體回收)
同Java語言一樣,Python使用了引用計數這一簡單技術來追蹤記憶體中的對象。
在Python內部記錄著所有使用中的對象各有多少引用。
一個內部跟蹤變數,稱為一個引用計數器。
當對象被建立時, 就建立了一個引用計數, 當這個對象不再需要時, 也就是說, 這個對象的引用計數變為0 時, 它被記憶體回收。但是回收不是"立即"的, 由解譯器在適當的時機,將垃圾對象佔用的記憶體空間回收。
a = 40 # 建立對象 <40>
b = a # 增加引用, <40> 的計數
c = [b] # 增加引用. <40> 的計數
del a # 減少引用 <40> 的計數
b = 100 # 減少引用 <40> 的計數
c[0] = -1 # 減少引用 <40> 的計數
垃 圾回收機制不僅針對引用計數為0的對象,同樣也可以處理循環參考的情況。循環參考指的是,兩個對象相互引用,但是沒有其他變數引用他們。這種情況下,僅使 用引用計數是不夠的。Python 的垃圾收集器實際上是一個引用計數器和一個迴圈垃圾收集器。作為引用計數的補充, 垃圾收集器也會留心被分配的總量很大(及未通過引用計數銷毀的那些)的對象。 在這種情況下, 解譯器會暫停下來, 試圖清理所有未引用的迴圈。
執行個體
解構函式 __del__ ,__del__在對象消逝的時候被調用,當對象不再被使用時,__del__方法運行:
#!/usr/bin/python
class Point:
def __init( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print class_name, "destroyed"
pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # 列印對象的id
del pt1
del pt2
del pt3
<pre>
<p>以上執行個體運行結果如下:</p>
<pre>
3083401324 3083401324 3083401324
Point destroyed
注意:通常你需要在單獨的檔案中定義一個類,
類的繼承
物件導向的編程帶來的主要好處之一是代碼的重用,實現這種重用的方法之一是通過繼承機制。繼承完全可以理解成類之間的類型和子類型關係。
需要注意的地方:繼承文法 class 衍生類別名(基類名)://... 基類名寫作括弧裡,基本類是在類定義的時候,在元組之中指明的。
在python中繼承中的一些特點:
1:在繼承中基類的構造(__init__()方法)不會被自動調用,它需要在其衍生類別的構造中親自專門調用。
2:在調用基類的方法時,需要加上基類的類名首碼,且需要帶上self參數變數。區別於在類中調用普通函數時並不需要帶上self參數
3:Python總是首先尋找對應類型的方法,如果它不能在衍生類別中找到對應的方法,它才開始到基類中逐個尋找。(先在本類中尋找調用的方法,找不到才去基類中找)。
如果在繼承元組中列了一個以上的類,那麼它就被稱作"多重繼承" 。
文法:
衍生類別的聲明,與他們的父類類似,繼承的基類列表跟在類名之後,如下所示:
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
執行個體:
#!/usr/bin/python
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print "Calling parent constructor"
def parentMethod(self):
print 'Calling parent method'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
class Child(Parent): # define child class
def __init__(self):
print "Calling child constructor"
def childMethod(self):
print 'Calling child method'
c = Child() # 執行個體化子類
c.childMethod() # 調用子類的方法
c.parentMethod() # 調用父類方法
c.setAttr(200) # 再次調用父類的方法
c.getAttr() # 再次調用父類的方法
以上代碼執行結果如下:
Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200
你可以繼承多個類
class A: # define your class A
.....
class B: # define your calss B
.....
class C(A, B): # subclass of A and B
.....
你可以使用issubclass()或者isinstance()方法來檢測。
issubclass() - 布爾函數判斷一個類是另一個類的子類或者子孫類,文法:issubclass(sub,sup)
isinstance(obj, Class) 布爾函數如果obj是Class類的執行個體對象或者是一個Class子類的執行個體對象則返回true。
重載方法
如果你的父類方法的功能不能滿足你的需求,你可以在子類重載你父類的方法:
執行個體:
#!/usr/bin/python
class Parent: # 定義父類
def myMethod(self):
print 'Calling parent method'
class Child(Parent): # 定義子類
def myMethod(self):
print 'Calling child method'
c = Child() # 子類執行個體
c.myMethod() # 子類調用重載方法
執行以上代碼輸出結果如下:
Calling child method
基礎重載方法
下表列出了一些通用的功能,你可以在自己的類重寫:
序號
方法, 描述 & 簡單的調用
1 __init__ ( self [,args...] )
建構函式
簡單的調用方法: obj = className(args)
2 __del__( self )
析構方法, 刪除一個對象
簡單的調用方法 : dell obj
3 __repr__( self )
轉化為供解譯器讀取的形式
簡單的調用方法 : repr(obj)
4 __str__( self )
用於將值轉化為適於人閱讀的形式
簡單的調用方法 : str(obj)
5 __cmp__ ( self, x )
對象比較
簡單的調用方法 : cmp(obj, x)
運算子多載
Python同樣支援運算子多載,執行個體如下:
#!/usr/bin/python
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
以上代碼執行結果如下所示:
Vector(7,8)
隱藏資料
在 python中實現資料隱藏很簡單,不需要在前面加什麼關鍵字,只要把類變數名或成員函數前面加兩個底線即可實現資料隱藏的功能,這樣,對於類的執行個體來 說,其變數名和成員函數是不能使用的,對於其類的繼承類來說,也是隱藏的,這樣,其繼承類可以定義其一模一樣的變數名或成員函數名,而不會引起命名衝突。 執行個體:
#!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
Python 通過改變名稱來包含類名:
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
Python不允許執行個體化的類訪問隱藏資料,但你可以使用object._className__attrName訪問屬性,將如下代碼替換以上代碼的最後一行代碼:
.........................
print counter._JustCounter__secretCount
執行以上代碼,執行結果如下:
1
2
2