python 的property函数

来源:互联网 发布:知柏地黄丸治疗性早熟 编辑:程序博客网 时间:2024/05/21 03:29
class C(object):def __init__(self):self._x = Nonedef getx(self):print ("get x")return self._xdef setx(self, value):print ("set x")self._x = valuedef delx(self):print ("del x")del self._xx = property(getx, setx, delx, "I'm the 'x' property.")


如果要使用property函数,首先定义class的时候必须是object的子类。通过property的定义,当获取成员x的值时,就会调用getx函数,当给成员x赋值时,就会调用setx函数,当删除x时,就会调用delx函数。使用属性的好处就是因为在调用函数,可以做一些检查。如果没有严格的要求,直接使用实例属性可能更方便。



>>> t=C()
>>> t.x
get x
>>> print (t.x)
get x
None
>>> t.x='en'
set x
>>> print (t.x)
get x
en
>>> del t.x
del x
>>> print (t.x)
get x

原创粉丝点击