• 【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'    
    

     

  • 相关阅读:
    Delegates in C#
    Continues Integration
    单例模式(Singleton Pattern)
    敏捷开发中编写高质量Java代码
    How to debug your application (http protocol) using Fiddler
    Java EE核心框架实战(1)
    03 Mybatis:01.Mybatis课程介绍及环境搭建&&02.Mybatis入门案例
    04 Spring:01.Spring框架简介&&02.程序间耦合&&03.Spring的 IOC 和 DI&&08.面向切面编程 AOP&&10.Spring中事务控制
    黑马IDEA版javaweb_22MySQL
    第04项目:淘淘商城(SpringMVC+Spring+Mybatis) 的学习实践总结【第二天】
  • 原文地址:https://www.cnblogs.com/lilip/p/10615571.html
Copyright © 2020-2023  润新知