python的property语法的使用

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

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

  2. 实现属性的gettersetter方法;


下面着重说明这两点:


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



首先请阅读下面的代码

1
2
3
4
5
6
7
8
9
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变成了类的属性,且它是只读的。效果如下:

python的property语法的使用


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


  • 实现属性的getter和setter方法


接着查看以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Array(object):
 
    def __init__(self, length=0, base_index=0):
        assert length >= 0
        self._data = [None for 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 selfself.get_base_index(),
        fset=lambda self, value: self.set_base_index(value)
    )

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

python的property语法的使用


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


  • 最后


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




本文转自 许大树 51CTO博客,原文链接:http://blog.51cto.com/abelxu/1874121,如需转载请自行联系原作者