详解python的property语法的使用方法

python中有一个property的语法,它类似于c#的get set语法,其功能有以下两点:

将类方法设置为只读属性;

实现属性的getter和setter方法;

下面着重说明这两点:

将类方法设置为只读属性

首先请阅读下面的代码

class book(object):
def __init__(self, title, author, pub_date):
self.title = title
self.author = author
self.pub_date = pub_date
@property
def des_message(self):
return u’书名:%s, 作者:%s, 出版日期:%s’ % (self.title, self.author, self.pub_date)

在这段代码中,将property作为一个装饰器修饰des_message函数,其作用就是将函数des_message变成了类的属性,且它是只读的。效果如下:

如上图所示,方法变成了属性,可以用访问属性的方式访问它。但是如果修改它的值,则会报错attributeerror错误,它是只读的

实现属性的getter和setter方法

接着查看以下代码:

class array(object):
def __init__(self, length=0, base_index=0):
assert length >= 0
self._data = [none for i in xrange(length)]
self._base_index = base_index
def get_base_index(self):
return self._base_index
def set_base_index(self, base_index):
self._base_index = base_index
base_index = property(
fget=lambda self: self.get_base_index(),
fset=lambda self, value: self.set_base_index(value)
)

这里我们给类array设置了一个base_index属性,它使用property实现了base_index的fget,fset功能,base_index是可读可写的,效果如下:

如上图所示,base_index是可读可写的。

最后

property是python的很好的语法特性,我们应该在编程中经常使用它。

以上就是详解python的property语法的使用方法的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类

发表评论