1. 程式人生 > 實用技巧 >Python property() 函式

Python property() 函式

描述

property()函式的作用是在新式類中返回屬性值。每組詞www.cgewang.com

語法

以下是 property() 方法的語法:

class property([fget[, fset[, fdel[, doc]]]])

引數

  • fget -- 獲取屬性值的函式
  • fset -- 設定屬性值的函式
  • fdel -- 刪除屬性值函式
  • doc -- 屬性描述資訊

返回值

返回新式類屬性。

例項

定義一個可控屬性值 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.")

如果cC的例項化, c.x 將觸發 getter,c.x = value 將觸發 setter , del c.x 觸發 deleter。

如果給定 doc 引數,其將成為這個屬性值的 docstring,否則 property 函式就會複製 fget 函式的 docstring(如果有的話)。

將 property 函式用作裝飾器可以很方便的建立只讀屬性:

class Parrot(object): def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage

上面的程式碼將 voltage() 方法轉化成同名只讀屬性的 getter 方法。

property 的 getter,setter 和 deleter 方法同樣可以用作裝飾器:

class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x

這個程式碼和第一個例子完全相同,但要注意這些額外函式的名字和 property 下的一樣,例如這裡的 x。