http://blog.csdn.net/jiyucn/article/details/2137679
對python中property函數的理解
下載了python-twitter-0.5的代碼,想學習一下別人是如何用python來開發一個開源項目的,發現確實沒找錯東西,首先代碼量少,一共才一個45k的源檔案,原檔案太多,看上去就有點頭疼,而且主要目的不是研究twitter api的實現。
該項目裡麵包含了以下內容:
1. 使用setup.py來build和setup
2. 包含了testcase的代碼,通過執行命令來完成單元測試
3. 代碼結構清晰,文檔寫得很好
4. 使用pydoc來製作文檔。
5. 包含api基本的使用方法。
今天主要是簡單閱讀了一下python-twitter的代碼,發現以前沒有接觸過的property函數,參見如下代碼:
class Status(object):
def __init__ (self,
created_at = None,
id = None,
text = None,
user = None,
now = None):
self.created_at = created_at
self.id = id
self.text = text
self.user = user
self.now = now
def GetCreatedAt(self):
return self._created_at
def SetCreatedAt(self, created_at):
self._created_at = created_at
created_at = property(GetCreatedAt, SetCreatedAt,
doc = ' The time this status message was posted. ' )
其中,對於類成員created_at就使用了property函數,翻看了python 2.5 document裡面對於property函數的解釋:
2.1 Built-in Functions
property( [fget[, fset[, fdel[, doc]]]])
Return a property attribute for new-style classes (classes that derive from object).
fget is a function for getting an attribute value, likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x:
class C(object):
def __init__ (self): self._x = None
def getx(self): return self._x
def setx(self, value): self._x = value
def delx(self): del self._x
x = property(getx, setx, delx, " I'm the 'x' property. " )
If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget's docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator:
大概含義是,如果要使用property函數,首先定義class的時候必須是object的子類。通過property的定義,當擷取成員x的值時,就會調用getx函數,當給成員x賦值時,就會調用setx函數,當刪除x時,就會調用delx函數。使用屬性的好處就是因為在調用函數,可以做一些檢查。如果沒有嚴格的要求,直接使用執行個體屬性可能更方便。
同時,還可以通過指定doc的值來為類成員定義docstring。
======================================================================================================
最下面的紅色字型部分
我的理解:下面這段文字是《Python基礎教程(第2版)》9.5節的內容。
其中講到使用者不應該關心類的實現方式。像文中的Rectangle()例子,類的屬性是width和height,如果讀寫size,需要調用訪問器方法(對應的get,set方法),但如果突然有一天類的實現方式變了,size是類的一個屬性,width和height是兩個臨時屬性時,要想讀寫width和height,就需要分別寫對應的get和set訪問器方法,還要修改所有使用width和height的位置。而property函數可以解決這一問題。紅括弧裡面的話是什麼意思呢。待驗證,。。。先幹活吧。