对python中property函数的理解

对python中property函数的理解 - A.TNG(阿唐)的博客:人生路漫漫,快乐先行 - 博客频道 - CSDN.NET

对python中property函数的理解

分类: 1.7 Python 6266人阅读 评论(0) 收藏 举报

对python中property函数的理解

下载了python-twitter-0.5的代码,想学习一下别人是如何用python来开发一个开源项目的,发现确实没找错东西,首先代码量少,一共才一个45k的源文件,原文件太多,看上去就有点头疼,而且主要目的不是研究twitter api的实现。
该项目里面包含了以下内容:
1. 使用setup.py来build和setup
2. 包含了testcase的代码,通过执行命令来完成单元测试
3. 代码结构清晰,文档写得很好
4. 使用pydoc来制作文档。
5. 包含api基本的使用方法。

今天主要是简单阅读了一下python-twitter的代码,发现以前没有接触过的property函数,参见如下代码:

 

class Status(object):
  
def __init__(self,
               created_at
=None,
               id
=None,
               text
=None,
               user
=None,
               now
=None):
    self.created_at 
= created_at
    self.id 
= id
    self.text 
= text
    self.user 
= user
    self.now 
= now

  
def GetCreatedAt(self):
    
return self._created_at

  
def SetCreatedAt(self, created_at):
    self._created_at 
= created_at

    created_at 
= property(GetCreatedAt, SetCreatedAt,
                        doc
='The time this status message was posted.')

                       
其中,对于类成员created_at就使用了property函数,翻看了python 2.5 document里面对于property函数的解释:

2.1 Built-in Functions
property( [fget[, fset[, fdel[, doc]]]])

Return a property attribute for new-style classes (classes that derive from object).
fget is a function for getting an attribute value, likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x:

 

class C(object):
    
def __init__(self): self._x = None
    
def getx(self): return self._x
    
def setx(self, value): self._x = value
    
def delx(self): del self._x
    x 
= property(getx, setx, delx, "I'm the 'x' property.")

If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget's docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator:

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

同时,还可以通过指定doc的值来为类成员定义docstring。 

原文地址:https://www.cnblogs.com/lexus/p/2790277.html