property函數

property函數用來在新式類中返回屬性值。

語法:class property(fget[,fset[,fdel[,doc]]])
參數:fget——獲取屬性值的函數
fset——設置屬性值的函數
fdel——刪除屬性值的函數
返回值:返回新式類屬性

eg:


In [18]: class C(object):
    ...:     def __init__(self):
    ...:         self._x = None
    ...:
    ...:     def getx(self):
    ...:         return self._x
    ...:
    ...:     def set_double(self, value):
    ...:         self._x = value*value
    ...:
    ...:     def delx(self):
    ...:         del self._x
    ...:
    ...:     x = property(getx, set_double, delx, "I'm the 'x' property.")

In [24]: c.x=2

In [25]: c.x
Out[25]: 2

還可以將property函數作爲裝飾器。

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