1 Introduction
Convert class method as a class attribute, you can use direct acquisition of property or property value assignment
Python's built @property decorator is responsible for the property to become a method call
2. Implement
class student(object):
@property
def score(self):
return self._score
@score.setter
def score(self,value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
stu=student()
stu.score=99
print(stu.score)
3. Summary
score increased (on) Method @property decorator is equivalent to score = property (fget = score), the score assigned to the property instance.
So, after the score was decorated, this is not an instance method score, but examples of the score property.
@property widely used in the definition of class, allowing the caller to write a short code, while ensuring the necessary checks on the parameters, so that the program is running it reduces the possibility of error.