python3 Advanced Programming (c) use @property

@propertyDecorator is responsible for the property to become a method call.

@propertyWidely 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 @propertyit at this time, @propertywhich 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 birthis a read-write property, and ageis a read-only property, because ageaccording to birththe current time is calculated.

Guess you like

Origin www.cnblogs.com/AndyChen2015/p/11388749.html