python之property函数

通常我们在访问和赋值属性的时候,都是在直接和类(实例的)的__dict__打交道,或者跟数据描述符等在打交道。但是假如我们要规范这些访问和设值方式的话,一种方法是引入复杂的数据描述符机制,另一种恐怕就是轻量级的数据描述符协议函数Property()。它的标准定义是:

  • property(fget=None,fset=None,fdel=None,doc=None)   

  • 前面3个参数都是未绑定的方法,所以它们事实上可以是任意的类成员函数

property()函数前面三个参数分别对应于数据描述符的中的__get__,__set__,__del__方法,所以它们之间会有一个内部的与数据描述符的映射。

http://bestchenwu.iteye.com/blog/1049842

  1. class C(object):  

  2.     def __init__(self):  

  3.         self._x = None  

  4.     def getx(self):  

  5.         print ("get x")  

  6.         return self._x  

  7.     def setx(self, value):  

  8.         print ("set x")  

  9.         self._x = value  

  10.     def delx(self):  

  11.         print ("del x")  

  12.         del self._x  

  13.     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.sina.com.cn/s/blog_a5c0cc7601018xzv.html

你可能感兴趣的:(python)