python的property语法的使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python的property语法的使用相关的知识,希望对你有一定的参考价值。

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

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

  2. 实现属性的gettersetter方法;


下面着重说明这两点:


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


首先请阅读下面的代码

# -*- coding:utf-8 -*-


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_indexfgetfset功能,base_index是可读可写的,效果如下:

技术分享

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


  • 最后

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


本文出自 “许大树” 博客,谢绝转载!

以上是关于python的property语法的使用的主要内容,如果未能解决你的问题,请参考以下文章

使用 Python 代码片段编写 LaTeX 文档

python基础语法15 组合,封装,访问限制机制,内置装饰器property

python 学习python语法的片段

Failed to convert property value of type ‘java.lang.String‘ to required type ‘int‘ for property(代码片段

python 装饰器语法糖(@classmethod @staticmethod @property @name.)原理剖析和运用场景

在下面的代码片段中的剩余 ='passthrough' 处的代码中出现语法错误