zoukankan      html  css  js  c++  java
  • 【python】面向对象编程之@property、@setter、@getter、@deleter用法

    @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'    
    

     

  • 相关阅读:
    腾讯实习前端工程师面经-一面-腾讯看点
    Redux的createStore实现
    GNU ARM 汇编基础
    python爬虫学习04-爬取贴吧
    python学习03-使用动态ua
    Python爬虫学习02--pyinstaller
    python爬虫学习01--电子书爬取
    简单的SQL语句学习
    微信小程序的五个生命周期函数
    python学习(12)使用正则表达式
  • 原文地址:https://www.cnblogs.com/lilip/p/10615571.html
Copyright © 2011-2022 走看看