zoukankan      html  css  js  c++  java
  • @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

  • 相关阅读:
    Unity apk开机自启动一次
    Unity调用Android
    实验 1 Linux 系统的安装和常用命令
    课堂测试3第一阶段数据清洗
    Tutorial_6 运行结果
    Command 'ifconfig' not found, but can be installed with: sudo apt install net-tools VM Ubuntu 解决方案
    《规划极限编程》阅读笔记03
    软件工程_个人课程总结
    《规划极限编程》阅读笔记02
    学习进度_第十六周
  • 原文地址:https://www.cnblogs.com/howhy/p/7158007.html
Copyright © 2011-2022 走看看