zoukankan      html  css  js  c++  java
  • 对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。 

  • 相关阅读:
    正则表达式(二):Unicode诸问题(上)
    ANT Notes
    Linux下OpenGL开发 -- 准备篇 (转)
    两个和尚
    Office 2008 for Mac 安装笔记
    从软件工程师到IT猎头:我的一点经历和感触 (转)
    One splitpath implementation (platform independent)
    ANT的使用(转)
    80后中专毕业奋斗10年 我的理财选择
    用ANT来实现邮件发送
  • 原文地址:https://www.cnblogs.com/lexus/p/2790277.html
Copyright © 2011-2022 走看看