Python uses @property adornment class method

Source: Internet
Author: User

Python version: 3.5.2

If we had a student class and defined a score attribute in it, but the score attribute would be revealed, there was no way to check the parameters, resulting in the result being arbitrarily changed:

stu = Student()stu.score = 9999

This is obviously illogical, in order to limit the scope of the score, you can set the score by a Set_score () method, and get the score by a Get_score () method, so that the parameter check can be achieved:

class Student(object):    def get_score(self):         return self._score    def set_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

The invocation and results are as follows:

调用:stu = Student()stu.set_score(99)print(stu.get_score())stu.set_score(9999)结果:99Traceback (most recent call last):    stu.set_score(9999)    raise ValueError('score must between 0 ~ 100!')ValueError: score must between 0 ~ 100!

However, the above method of invocation is slightly more complex, and it is not straightforward to use attributes directly.

This problem can be solved, the adorner can give the function dynamic add function, then for the class method, the same can work, you can use the @property adorner to turn the class method into a property to invoke:

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 turn a Get method into a property, just add @property to it, and at this point, @ The property itself creates another adorner @score.setter, which is responsible for making the Set method a property and can be assigned, and then we can directly manipulate the properties of the score with parameter checking:

调用:stu = Student()stu.score = 99print(stu.score)stu.score = 9999结果:99Traceback (most recent call last):    stu.score = 9999    raise ValueError('score must between 0 ~ 100!')ValueError: score must between 0 ~ 100!

With this @property, we can manipulate the properties of the class without concern.

If we define only the Get method in the class (and decorate it with @property) and do not define the set method, then this property becomes a read-only property.

@property is widely used in the definition of a class, allowing the caller to write short code while guaranteeing the necessary checks on the parameters, thus reducing the likelihood of errors when the program runs.

Python uses @property adornment class method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.