http://blog.youkuaiyun.com/jiyucn/article/details/2137679
对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。
======================================================================================================
最下面的红色字体部分
我的理解:下面这段文字是《Python基础教程(第2版)》9.5节的内容!
其中讲到用户不应该关心类的实现方式。像文中的Rectangle()例子,类的属性是width和height,如果读写size,需要调用访问器方法(对应的get,set方法),但如果突然有一天类的实现方式变了,size是类的一个属性,width和height是两个临时属性时,要想读写width和height,就需要分别写对应的get和set访问器方法,还要修改所有使用width和height的位置!而property函数可以解决这一问题?红括号里面的话是什么意思呢?待验证,。。。先干活吧!
本文介绍了Python中property函数的应用及其实现原理。通过对一个具体示例的分析,展示了如何使用property函数来创建受控属性,使得类的成员变量可以通过自定义的get和set方法进行访问和设置。
2873

被折叠的 条评论
为什么被折叠?



