Python property() 函數的使用方法

class C:
    def __init__(self,size=100):
        self.size = size
    def getx(self):
        return self.size
    def setx(self,value):
        self.size = value
    def delx(self):
        del self.size
    x = property(getx,setx,delx)

#如果c是C的實例化,c.x將觸發getx, x=value將觸發setx, del c.x將觸發delx。

>>>c=C()       #類的實例化
>>>c.x         #調用property的第1個方法
100
>>>c.x = 200   #調用property的第2個方法
>>>c.x
200
>>>del c.x      #調用property的第3個方法
c.x
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 5, in getx
AttributeError: 'C' object has no attribute 'size'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章