Understanding of the python @property

@property role:

      We define a class, they often have some of the attributes of the class read and modify , we can easily use something like this: Object Properties such a way to achieve our objective, but this approach is not safe , because when the user attribute modification operations, the input value of the user without any verification , data type and value range completely uncontrollable, the user arbitrarily inputs may be disastrous consequences . As shown in the following:

class Student:
    def __init__(self, name, score):
        self.name = name
        self._score = score

s = Student('Bob', 59)
s._score = 60
s._score = 1000 #这个分数肯定是有误的

      We can do this:

 

class Student:
    def __init__(self, name, score):
        self.name = name
        self._score = score
    def get_score(self):
        return self._score
    def set_score(self, score):
        if not isinstance(value,int)
            raise ValueError('score must be integer')
        if score < 0 or score > 100:
            raise ValueError('invalid score')
        self._score = score

      As a result, s.set_score (1000) will throw an error. See Figure methods defined in the new code, Java learned readers will feel very familiar, is not this Java Bean specification it? In fact, in addition to appear similar, the two are not the same. Usually in Java class variable is set to private property , and in the class defines getter and setter methods in external only through getter and setter methods to access the property value , the benefits of doing so is to ensure the safety properties of the variable value . The python and no private variables of the concept , although the figure above rewritten to achieve the function of input validation, but to write a bit cumbersome , user-friendly is not enough. Python provides a more excellent solutions "@property". Because Python supports higher-order functions, you can use decorator function to get / set methods "decoration" to attribute call:

     

class Student:
    def __init__(self, name, score):
        self.name = name
        self._score = score
    @property
    def score(self):
        return self._score
    
    @score.setter
    def score(self, score):
        if score < 0 or score > 100:
            raise ValueError('invalid score')
        self._score = score

      

      Note: The first score (self) is a get method, decorated with @property second score (self, score) is set method, @ score.setter decorative, @ score.setter after previous decorative @property by-product. Now, you can be like using the property set as the score:

      Careful readers will find on the map Student class two methods were exactly the same , but after using the @ score.setter @property and decorative, not only can go hand in hand, but also greatly simplify access to the properties outside the class, which is what the magic python syntax sugar.

      

>>> s = Student('Bob', 59)
>>> s.score = 60
>>> print s.score
60
>>> s.score = 1000
Traceback (most recent call last):
  ...
ValueError: invalid score

remind:

      score () method after using "@property" decorator has become a kind of common property, the property will conflict with the original score , it is recommended that the reader usually develop good habits when writing code that is used when defining class attributes underscore as a prefix .

Guess you like

Origin blog.csdn.net/qq_28019007/article/details/94738829