Understanding and use of @property in python

When looking at the code of the great god on git, there is such a paragraph:

Then I was very curious about what it was. Then I went to Baidu and checked a lot of information, but I didn't understand it clearly. Finally, I slowly realized that this is equivalent to a restricted use. The example I found on the Internet is probably:

  1. class Student(object):
  2. def get_score(self):
  3. return self._score
  4. def set_score(self, value):
  5. if not isinstance(value, int):
  6. raise ValueError('score must be an integer!')
  7. if value < 0 or value > 100:
  8. raise ValueError('score must between 0 ~ 100!')
  9. self._score = value

In normal use, it should be:



That is to say, the age of the student is limited here, and then an age is given at random to see if it matches the age of the student. It needs to run two steps each time.

Then using @property can simplify a bit

  1. class Student(object):
  2. @property
  3. def score(self):
  4. return self._score
  5. @score.setter
  6. def score(self,value):
  7. if not isinstance(value, int):
  8. raise ValueError( 'The fraction must be an integer' )
  9. if value < 0 or value > 100:
  10. raise ValueError( 'The score must be between 0-100' )
  11. self._score = value

When running, just run

>>>Student().score = 60



In general:@propertyWidely used in class definitions, it allows the caller to write short code while ensuring the necessary checks for parameters, thus reducing the possibility of errors when the program is running. That is, the determination of the value is carried out directly. Eliminates the step of judging whether the value is correct

<<Resources are excerpted from the website of Liao Dashen>>


Related: Understanding and use of @property in python