iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >【python】面向对象编程之@prop
  • 605
分享到

【python】面向对象编程之@prop

面向对象pythonprop 2023-01-31 00:01:03 605人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

  @property装饰器作用:把一个方法变成属性调用 使用@property可以实现将类方法转换为只读属性,同时可以自定义setter、getter、deleter方法   @property&@.setter class

 

@property装饰器作用:把一个方法变成属性调用

使用@property可以实现将类方法转换为只读属性,同时可以自定义setter、getter、deleter方法

 

@property&@.setter

class Person(object):
    
    @property
    def birth(self):
        return self._birth

    @birth.setter
    def birth(self,value):
        self._birth=value

if __name__ == '__main__':
    p=Person()
    p.birth=1985
    print(p.birth)

---------------运行结果-----------------
1985

  

把方法变成属性,只需要在方法前添加@property装饰器即可。

继续添加一个装饰器@birth.setter,给属性赋值

 

@.getter

上例中因为在birth方法中返回了birth值,所以即使不调用getter方法也可以获得属性值。接下来再将函数稍作修改,看下getter方法是怎么使用的。

class Person(object):
    
    @property
    def birth(self):
        return 'my birthday is a secret!'

    @birth.setter
    def birth(self,value):
        self._birth=value

if __name__ == '__main__':
    p=Person()
    p.birth=1985
    print(p.birth)

------------------运行结果------------------
my birthday is a secret!

  

因为将birth方法的返回值写了固定值,所以即使赋值成功,但是并不会打印。

如果想打印出具体的值,可以增加getter方法。

class Person(object):
    
    @property
    def birth(self):
        return self._birth

    @birth.setter
    def birth(self,value):
        self._birth=value

    @birth.getter
    def birth(self):
        return self._birth

if __name__ == '__main__':
    p=Person()
    p.birth=1985
    print(p.birth)

------------------运行结果-------------------
1985

 

@.deleter

@property含有一个删除属性的方法

class Person(object):
    
    @property
    def birth(self):
        return self._birth

    @birth.setter
    def birth(self,value):
        self._birth=value

    @birth.getter
    def birth(self):
        return self._birth
    
    @birth.deleter
    def birth(self):
        del self._birth

if __name__ == '__main__':
    p=Person()
    p.birth=1985
    print(p.birth)
    del p.birth
    print(p.birth)


---------------运行结果-----------------
1985

#删除birth属性后,再次访问会报错
AttributeError: 'Person' object has no attribute '_birth'    

 

--结束END--

本文标题: 【python】面向对象编程之@prop

本文链接: https://www.lsjlt.com/news/181611.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作