您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/4/5 14:32:17发布33次查看
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语法的使用方法的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product