python之property函数
python之property函数
http://blog.sina.com.cn/s/blog_a5c0cc7601018xzv.html
通常我们在访问和赋值属性的时候,都是在直接和类(实例的)的__dict__打交道,或者跟数据描述符等在打交道。但是假如我们要规范这些访问和设值方式的话,一种方法是引入复杂的数据描述符机制,另一种恐怕就是轻量级的数据描述符协议函数Property()。它的标准定义是:
- property(fget=None,fset=None,fdel=None,doc=None)
- 前面3个参数都是未绑定的方法,所以它们事实上可以是任意的类成员函数
property()函数前面三个参数分别对应于数据描述符的中的__get__,__set__,__del__方法,所以它们之间会有一个内部的与数据描述符的映射。
http://bestchenwu.iteye.com/blog/1049842
------------------------------------------------------------------------------------------------
- class C(object):
- def __init__(self):
- self._x = None
- def getx(self):
- print ("get x")
- return self._x
- def setx(self, value):
- print ("set x")
- self._x = value
- def delx(self):
- print ("del x")
- del self._x
- x = 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
http://blog.csdn.net/yatere/article/details/6658457
浙公网安备 33010602011771号