现在的位置: 首页 > 综合 > 正文

py property

2013年09月17日 ⁄ 综合 ⁄ 共 582字 ⁄ 字号 评论关闭

# -*- coding: cp936 -*-
"""
如果要让python支持中文 务必在其头文件加  上一句
"""
'''
如果要使用property函数,首先定义class的时候必须是object的子类。
通过property的定义,当获取成员x的值时,就会调用getx函数,
当给成员x赋值时,就会调用setx函数,当删除x时,就会调用delx函数。
使用属性的好处就是因为在调用函数,可以做一些检查。如果没有严格的要求,
直接使用实例属性可能更方便。
同时,还可以通过指定doc的值来为类成员定义docstring。

'''
class My(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 am the property")
 
t = My()
print t.x
t.x = "tang"
print t.x
del t.x

 

 

抱歉!评论已关闭.