@property
Decorator is responsible for the property to become a method call.
@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 reduces the likelihood of errors
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
To become a property getter method, just add @property
it at this time, @property
which in turn created another decorator @score.setter
, is responsible for assigning attributes to become a setter method, so we have a property controlled operation:
S = >>> Student () >>> s.score = 60 # the OK, the actual conversion is s.set_score (60) >>> s.score # the OK, the actual conversion is s.get_score () 60 >>> S = 9999 .score Traceback (MOST Recent Last Call): ... a ValueError: Score MUST BETWEEN 0 ~ 100!
You can define the read-only attribute, define only getter method, does not define a setter method is a read-only property:
class Student(object): @property def birth(self): return self._birth @birth.setter def birth(self, value): self._birth = value @property def age(self): return 2015 - self._birth
The above birth
is a read-write property, and age
is a read-only property, because age
according to birth
the current time is calculated.