Python practical Note (23) object-oriented advanced programming-using @property

Source: Internet
Author: User

This is obviously illogical. To limit the scope of the score, you can set the score by one method, and set_score() then get the score by one, get_score() so that in the set_score() method, you can check the parameters:

 class studentdef get_scorereturn self._score def set_scoreif not Isinstance (value, int): raise valueerror ( ' score must is an integer! ') if value < 0 or value >  100: span class= "keyword" >raise valueerror ( ' score must between 0 ~ 100! ') Self._score = value  span>                 

Remember the adorner (decorator) can add functionality to a function dynamically? For class methods, adorners work as well. Python's built-in @property adorner is responsible for turning a method into a property call:

class student (object): @ Property def scorereturn self._score  @score. Setter def score (self, value): if not isinstance (value, int): raise valueerror (if value < 0 or value >  : raise valueerror ( ' score must between 0 ~ 100! ') Self._score = value
                                            

@propertyImplementation is more complex, we first examine how to use. To turn a getter method into a property, just add it, and @property at this point, it @property creates another adorner @score.setter , which is responsible for turning a setter method into a property assignment, so we have a controllable property operation:

>>> s = Student()>>> s.score = 60 # OK,实际转化为s.set_score(60)>>> s.score # OK,实际转化为s.get_score()60>>> s.score = 9999Traceback (most recent call last): ...ValueError: score must between 0 ~ 100!

Notice that this magical @property , when we operate on instance properties, we know that this property is probably not directly exposed, but is implemented through getter and setter methods.

Python practical Note (23) object-oriented advanced programming-using @property

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.