Python property() 函數
描述
property() 函數的作用是在新式類中返回屬性值。
語法
以下是 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.")
如果 c 是 C 的實例化, 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。