• @property和@x.setter和@x.deleter表示可读可写可删除


    @property可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式,但是有时候setter/deleter也是需要的。
    1》只有@property表示只读。
    2》同时有@property和@x.setter表示可读可写。

    3》同时有@property和@x.setter和@x.deleter表示可读可写可删除。

    [python] view plain copy
     
    1. class student(object):  #新式类  
    2.     def __init__(self,id):    
    3.         self.__id=id    
    4.     @property  #读    
    5.     def score(self):    
    6.         return self._score    
    7.     @score.setter #写    
    8.     def score(self,value):    
    9.         if not isinstance(value,int):    
    10.             raise ValueError('score must be an integer!')      
    11.         if value<or value>100:    
    12.             raise ValueError('score must between 0 and 100')     
    13.         self._score=value    
    14.     @property #读(只能读,不能写)    
    15.     def get_id(self):    
    16.         return self.__id    
    17.     
    18. s=student('123456')    
    19. s.score=60 #写    
    20. print s.score #读    
    21. #s.score=-2 #ValueError: score must between 0 and 100    
    22. #s.score=32.6 #ValueError: score must be an integer!    
    23. s.score=100 #写    
    24. print s.score #读    
    25. print s.get_id #读(只能读,不可写)  
    26. #s.get_id=456 #只能读,不可写:AttributeError: can't set attribute  

    运行结果:
    60
    100
    123456

  • 相关阅读:
    (OK) usbip-utils
    How To Set Up A USB-Over-IP Server And Client With Ubuntu 10.04
    linux内核模块获取设备IP地址
    (OK) 国内常用NTP服务器地址及IP
    2017年我国将开始部署和建设IPv6地址项目
    C++之STL和Boost
    linux内核IOCTL网络控制框架实现分析
    2016年 AI 技术发展综述
    2016年SDN/NFV开源三大趋势
    Angular
  • 原文地址:https://www.cnblogs.com/howhy/p/7158007.html
Copyright © 2020-2023  润新知