When binding a property, if we expose the property directly to the outer surface, it can cause the property to be arbitrarily modified, sometimes this is what we do not want to see
such as: setting students ' grades
class Student (object): def __init__ (self): = 0
#这个显然不符合属性的规范
#std = Student ()
#std. score = 99999
#print Std.score
#于是我们采用内部限制的方法来设定
1 classStudent2 (object):2 def __init__(self):3 Pass4 5 defGet_score (self):6 returnSelf._score7 8 defSet_score (self, value):9 if notisinstance (value, int):Ten RaiseValueError ('score must is an integer!') One ifValue < 0orValue > 100: A RaiseValueError ('score must between 0 ~ 100!') -Self._score =value - the -STD2 =Student2 () -Std2.set_score (60) - PrintStd2.get_score ()# - + -Std2.set_score (99999) + PrintStd2.get_score () A at Traceback (most recent): -File"/home/mywork/oldboy/practice/property.py", line 44,inch<module> -Std2.set_score (99999) -File"/home/mywork/oldboy/practice/property.py", line 35,inchSet_score - RaiseValueError ('score must between 0 ~ 100!') -Valueerror:score must between 0 ~ 100!
#但是, the above call method is slightly more complex, which is the need to apply @property
#他的本质就是把一个getter方法变成属性
#此时, the @property itself creates another adorner @score.setter,
#负责把一个setter方法变成属性赋值, so we have a controllable property operation:
Look at the code:
1 classStudent3 (object):2 3 @property4 defscore (self):5 returnSelf._score6 7 @score. Setter8 defscore (self, value):9 if notisinstance (value, int):Ten RaiseValueError ('score must is an integer!') One ifValue < 0orValue > 100: A RaiseValueError ('score must between 0 ~ 100!') -Self._score =value - theSTD3 =Student3 () -Std3.score = 90 - PrintStd3.score# - -Std3.score = 9000#error when setting directly + - Traceback (most recent): +File"/home/mywork/oldboy/practice/property.py", line 69,inch<module> AStd3.score = 9000 atFile"/home/mywork/oldboy/practice/property.py", line 63,inchscore - RaiseValueError ('score must between 0 ~ 100!') -Valueerror:score must between 0 ~ 100!
The use of @property in Python