Getting started with python (@property, @*.setter)

@property can access functions defined by python "as" properties, thus providing a more friendly access method, but sometimes setters/deleters are also needed.
1. Only @property means read-only .
2. Both @property and @*.setter indicate read and write .

3. At the same time, @property and @*.setter and @*.deleter indicate readable, writable and deleteable .


Code:

[python]  view plain copy  
  1.  1#coding=utf-8   
  2.  2 class  student(object):   #Need to inherit the parent class object, otherwise the property will not take effect    
  3.  3   
  4.  4def __init__(self,v_id = '000'):       
  5.  5self.__id = v_id           
  6.  6   
  7.  7     @property  
  8.  8def score(self):       
  9.  9returnself._score            
  10. 10   
  11. 11     @score.setter  
  12. 12def score(self,v_score):       
  13. 13ifnot isinstance(v_score,int):            
  14. 14raise ValueError('score must be an integer!')               
  15. 15if v_score < 0or v_score > 100:            
  16. 16#raise ValueError('score must between 0 and 100')                    
  17. 17 print ( 'The value is not within the valid range' )               
  18. 18else:           
  19. 19print(v_score,'operation success')               
  20. 20self._score = v_score           
  21. 21   
  22. 22     @property  
  23. 23def get_id(self):       
  24. 24 return loan .__ id            
  25. 25   
  26. 26 s = student('001')  
  27. 27 s.score=60  
  28. 28 #print s.__id #Error, there is no such attribute   
  29. 29print s.get_id   
  30. 30print s.score   
  31. 31   
  32. 32 s = student()  
  33. 33 s.score=-100  
  34. 34print s.get_id   
  35. 35print s.score   

implement:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324768191&siteId=291194637