Python中的property类与@property装饰器

class property(fget=None, fset=None, fdel=None, doc=None)

  • 返回一个property属性

  • fget:获取属性值

  • fset:设置属性值

  • fdel:删除属性

  • doc:属性描述

注意,如果设置了doc参数,则参数值就是属性的docstring,否则系统将会读取fget参数的docstring(如果存在)作为属性的docstring,下面会示例说明(参见图一)

property典型用法是定义托管属性

class C:
    def __init__(self):
        self._x = None

    def get_x(self):
        """I'm get_x method"""
        print('get_x invoked')
        return self._x

    def set_x(self, value):
        print('set_x invoked')
        self._x = value

    def del_x(self):
        print('del_x invoked')
        del self._x

    # 设置doc参数
    x = property(get_x, set_x, del_x, "I'm the 'x' property.")
    # 不设置doc参数
    x0 = property(get_x, set_x, del_x)

验证代码

if __name__ == '__main__':
    c = C()
    print(help(c))
    c.x = '100'
    c.x
    del c.x

执行结果:

这里写图片描述

从上面的代码执行结果中,我们可以看到:对于类property,如果设置了doc参数,则参数值就是属性的docstring,否则系统将会读取fget参数的docstring(如果存在)作为属性的docstring,因此,我们可以使用@property装饰器来创建只读属性,@property装饰器会将方法转换为相同名称的只读属性。

class Parrot:
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

这里写图片描述
一个property对象包含三个方法:getter, setter, deleter,当一个函数被@property装饰器修饰时,系统会自动创建一个包含对应访问函数的同名属性,我们示例说明:

class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

上述示例与本章第一个例子定义一样

https://docs.python.org/3/library/functions.html#property

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值