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