Python 3 教程
property() 函數(shù)的作用是在新式類中返回屬性值。
以下是 property() 方法的語法:
class property([fget[, fset[, fdel[, doc]]]])
返回新式類屬性。
如果 c 是 C 的實例化, c.x 將觸發(fā) getter,c.x = value 將觸發(fā) setter , del c.x 觸發(fā) deleter。
如果給定 doc 參數(shù),其將成為這個屬性值的 docstring,否則 property 函數(shù)就會復(fù)制 fget 函數(shù)的 docstring(如果有的話)。
將 property 函數(shù)用作裝飾器可以很方便的創(chuàng)建只讀屬性:
上面的代碼將 voltage() 方法轉(zhuǎn)化成同名只讀屬性的 getter 方法。
property 的 getter,setter 和 deleter 方法同樣可以用作裝飾器:
這個代碼和第一個例子完全相同,但要注意這些額外函數(shù)的名字和 property 下的一樣,例如這里的 x。
其他擴(kuò)展