python装饰器@property

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

3、同时有@property和@*.setter和@*.deleter表示可读可写可删除


代码:

[python]  view plain  copy
  1.  1 #coding=utf-8  
  2.  2 class student(object):  #需继承父类object,否则property等无法生效   
  3.  3   
  4.  4     def __init__(self,v_id = '000'):  
  5.  5         self.__id = v_id  
  6.  6   
  7.  7     @property  
  8.  8     def score(self):  
  9.  9         return self._score  
  10. 10   
  11. 11     @score.setter  
  12. 12     def score(self,v_score):  
  13. 13         if not isinstance(v_score,int):  
  14. 14             raise ValueError('score must be an integer!')  
  15. 15         if v_score < 0 or v_score > 100:  
  16. 16             #raise ValueError('score must between 0 and 100')       
  17. 17             print('数值不在有效范围内')  
  18. 18         else:  
  19. 19             print(v_score,'operation success')  
  20. 20         self._score = v_score  
  21. 21   
  22. 22     @property  
  23. 23     def get_id(self):  
  24. 24         return self.__id  
  25. 25   
  26. 26 s = student('001')  
  27. 27 s.score=60  
  28. 28 #print s.__id   #报错,没有该属性  
  29. 29 print s.get_id  
  30. 30 print s.score  
  31. 31   
  32. 32 s = student()  
  33. 33 s.score=-100  
  34. 34 print s.get_id  
  35. 35 print s.score  

执行:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值