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  

执行:

目录
相关文章
|
9月前
|
测试技术 Python
Python装饰器:为你的代码施展“魔法”
Python装饰器:为你的代码施展“魔法”
392 100
|
10月前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
389 101
|
10月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
315 99
|
9月前
|
缓存 Python
Python装饰器:为你的代码施展“魔法
Python装饰器:为你的代码施展“魔法
518 88
|
10月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
556 98
|
10月前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
10月前
|
缓存 测试技术 Python
解锁Python超能力:深入理解装饰器
解锁Python超能力:深入理解装饰器
230 2
|
10月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
1635 102
|
10月前
|
数据采集 机器学习/深度学习 算法框架/工具
Python:现代编程的瑞士军刀
Python:现代编程的瑞士军刀
503 104
|
10月前
|
人工智能 自然语言处理 算法框架/工具
Python:现代编程的首选语言
Python:现代编程的首选语言
392 103

推荐镜像

更多