Python---很強悍的property,絕對的強大

轉自:http://www.cnblogs.com/lovemo1314/archive/2011/05/03/2035600.html

假設定義了一個類:C,該類必須繼承自object類,有一私有變量_x
class C:
 def init(self):
  self.__x=None
  1.現在介紹第一種使用屬性的方法:
  在該類中定義三個函數,分別用作賦值、取值和刪除變量(此處表達也許不很清晰,請看示例)
 def getx(self):
  return self.__x
 def setx(self,value):
  self.__x=value
 def delx(self):
  del self.__x
 x=property(getx,setx,delx,”)
property函數原型爲property(fget=None,fset=None,fdel=None,doc=None),所以根據自己需要定義相應的函數即可。
  現在這個類中的x屬性便已經定義好了,我們可以先定義一個C的實例c=C(),然後賦值c.x=100,取值y=c.x,刪除:del c.x。是不是很簡單呢?請看第二種方法
  2.下面看第二種方法(在2.6中新增)
  首先定義一個類C:
class C:
 def init(self):
  self.__x=None
  下面就開始定義屬性了
 @property
 def x(self):
  return self.__x
 @x.setter
 def x(self,value):
  self.__x=value
 @x.deleter
 def x(self):
  del self.__x
 同一屬性的三個函數名要相同哦。

轉自:http://joy2everyone.iteye.com/blog/910950
@property 可以將python定義的函數“當做”屬性訪問,從而提供更加友好訪問方式,但是有時候setter/getter也是需要的,我們視具體情況吧

請注意以下代碼場景:

代碼片段1:
Python2.6代碼
class Parrot(object):
def init(self):
self._voltage = 100000

@property  
def voltage(self):  
    """Get the current voltage."""  
    return self._voltage  

if name == “main“:
# instance
p = Parrot()
# similarly invoke “getter” via @property
print p.voltage
# update, similarly invoke “setter”
p.voltage = 12

代碼片段2:
Python2.6代碼
class Parrot:
def init(self):
self._voltage = 100000

@property  
def voltage(self):  
    """Get the current voltage."""  
    return self._voltage  

if name == “main“:
# instance
p = Parrot()
# similarly invoke “getter” via @property
print p.voltage
# update, similarly invoke “setter”
p.voltage = 12

代碼1、2的區別在於
class Parrot(object):

在python2.6下,分別運行測試
片段1:將會提示一個預期的錯誤信息 AttributeError: can’t set attribute
片段2:正確運行

參考python2.6文檔,@property將提供一個ready-only property,以上代碼沒有提供對應的@voltage.setter,按理說片段2代碼將提示運行錯誤,在python2.6文檔中,我們可以找到以下信息:

BIF:
property([fget[, fset[, fdel[, doc]]]])
Return a property attribute for new-style classes (classes that derive from object).
原來在python2.6下,內置類型 object 並不是默認的基類,如果在定義類時,沒有明確說明的話(代碼片段2),我們定義的Parrot(代碼片段2)將不會繼承object

而object類正好提供了我們需要的@property功能,在文檔中我們可以查到如下信息:

new-style class
Any class which inherits from object. This includes all built-in types like list and dict. Only new-style classes can use Python’s newer, versatile features like slots, descriptors, properties, and getattribute().

同時我們也可以通過以下方法來驗證
Python 2.6代碼
class A:
pass

type(A)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章