python中property函数_对python中property函数的理解

对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函数,参见如下代码:

None.gifclassStatus(object):

None.gifdef__init__(self,

None.gif created_at=None,

None.gif id=None,

None.gif text=None,

None.gif user=None,

None.gif now=None):

None.gif self.created_at=created_at

None.gif self.id=id

None.gif self.text=text

None.gif self.user=user

None.gif self.now=now

None.gif

None.gifdefGetCreatedAt(self):

None.gifreturnself._created_at

None.gif

None.gifdefSetCreatedAt(self, created_at):

None.gif self._created_at=created_at

None.gif

None.gif created_at=property(GetCreatedAt, SetCreatedAt,

None.gif doc='The time this status message was posted.')

None.gif

None.gif

其中,对于类成员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:

None.gifclassC(object):

None.gifdef__init__(self): self._x=None

None.gifdefgetx(self):returnself._x

None.gifdefsetx(self, value): self._x=value

None.gifdefdelx(self):delself._x

None.gif 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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值