Python property() 函数的使用方法

穿精又带淫゛_ 提交于 2020-01-29 00:43:21
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'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!